Python

Receive aemail containing the next unit.

Introduction to Object-Oriented Programming

Understanding Class and Objects in Python

general-purpose programming language

General-purpose programming language.

Python is an object-oriented programming language. This means that almost all the code is implemented using a special construct called classes. Programmers use classes to keep related things together. This is done using the keyword class, which is a grouping of object-oriented constructs.

What is a Class?

A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python, a class is created by the keyword class.

An object is created using the constructor of the class. This object will then be called the instance of the class.

Creating a Class in Python

In Python, a class is created by the keyword class. An object is created using the constructor of the class. This object will then be called the instance of the class.

class MyClass: x = 5

Creating an Object in Python

You can create an object of the above class as follows:

p1 = MyClass() print(p1.x)

Understanding the __init__ method

In Python, __init__ is a special method which is automatically called when an object of that Class is created. We use the __init__ method to initialize the attributes of an object.

class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age)

Object Methods

Objects can also contain methods. Methods in objects are functions that belong to the object.

class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) p1.myfunc()

The self Parameter

The self parameter is a reference to the current instance of the class and is used to access variables that belong to the class.

It does not have to be named self, you can call it whatever you like, but it has to be the first parameter of any function in the class.

class Person: def __init__(mysillyobject, name, age): mysillyobject.name = name mysillyobject.age = age def myfunc(abc): print("Hello my name is " + abc.name) p1 = Person("John", 36) p1.myfunc()

By the end of this unit, you should have a solid understanding of classes and objects in Python, and you should be able to create and use them in your programs.