Introduction
Python is an object oriented programming language. Unlike procedure oriented programming, where the main emphasis is on functions, object oriented programming stress on objects. An object is also called an instance of a class and the process of creating this object is called instantiation. Attributes of class are data members (class variables and instance variables) and methods which are accessed via dot notation.
- Class variable is a variable that is shared by all the different objects/instances of a class.
- Instance variables are variables which are unique to each instance. It is defined inside a method and belongs only to the current instance of a class.
- Methods are also called as functions which are defined in a class and describes the behaviour of an object.
Defining a Class
One can define a class using the keyword class. The first string is called docstring and has a brief description about the class. Although not mandatory, this is recommended. A class creates a new local namespace where all its attributes are defined. There are also special attributes in it that begins with double underscores (__).
class MyClass: "This is myClass" a = 10 def func(self): print('Hello') # Output: 10 print(MyClass.a) # Output: 'This is myClass' print(MyClass.__doc__) # Create new object instances ob = MyClass() # Output: Hello ob.func()
self
parameter in function definition inside the class, but ob.func() called without any arguments. This is because, whenever an object calls its method, the object itself is passed as the first argument. So, ob.func() translates into MyClass.func(ob). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument. For these reasons, the first argument of the function in class must be the object itself. This is conventionally called self.
Constructors
Special function __init__()
gets called whenever a new object of that class is instantiated. This type of function is also called constructors in Object Oriented Programming (OOP). We normally use it to initialize all the variables. Any attribute of an object can be deleted anytime, using the del
statement.
class ComplexNumber: def __init__(self,r = 0,i = 0): self.real = r self.imag = i def getData(self): print("{0}+{1}j".format(self.real, self.imag)) # Create new object c = ComplexNumber(2,3) # Output: 2+3j c.getData() # Delete 'img'. Accessing i.e. c.getData() will throw error del c.imag
On the command del c1
, this binding is removed and the name c1 is deleted from the corresponding namespace. The object however continues to exist in memory and if no other name is bound to it, it is later automatically destroyed. This automatic destruction of unreferenced objects in Python is also called garbage collection.