My Blog
Articles related to programming, computer science, technology and research.

19/04/2018 Categories: Python Programming. No Comments on Object Oriented Programming in Python

Introduction to Classes and Objects

 

Classes and objects are the two basic concepts in object oriented programming. An object is an instance of a class. A class creates a new type and provides a blueprint or a template using for creating objects. In Python we already know that everything is an object of some class. In Python, the base class for all classes is object.

 

Creating or Defining a Class

 

The syntax for a class is as follows:

 

 

The statements in the syntax can be variables, control statements, or function definitions. The variables in a class are known as class variables. The functions defined in a class are known as class methods. Class variables and class methods are together called as class members.

 

The class methods can access all class variables. The class members can be accessed outside the class by using the object of that class. A class definition creates a new namespace.

 

Creating Objects

 

Once a class is defined, we can create objects for it. Syntax for creating an object is as follows:

 

 

Creating an object for a class is known as instantiation. We can access the class members using an object along with the dot (.) operator as follows:

 

 

Following code creates a student class and one object s which is used to access the members of student class:

 

 

Class Variables and Instance Variables

 

Variables which are created inside a class and outside methods are known as class variables. Class variables are common for all objects. So, all objects share the same value for each class variable. Class variables are accessed as ClassName.variable_name.

 

Variables created inside the class methods and accessed using the  self variable are known as instance variables. Instance variable value is unique to each object. So, the values of instance variables differ from one object to the other. Consider the following class:

 

 

In the above Student class, branch is a class variable and regdno and name are instance variables.

 

Public and Private Instance Variables

 

By default instance variables are public. They are accessible throughout the class and also outside the class. An instance variable can be made private by using _ _ (double underscore) before the variable name. Private instance variables can be accessed only inside the class and not outside the class. Following example demonstrates private instance variable:

 

 

self Argument

 

The self  argument is used to refer the current object (like this keyword in C and Java). Generally, all class methods by default should have at least one argument which should be the self argument. The self variable or argument is used to access the instance variables or object variables of an object.

 

__init__() Method (Constructor)

 

The __init__() is a special method inside a class. It serves as the constructor. It is automatically executed when an object of the class is created. This method is used generally to initialize the instance variables, although any code can be written inside it.

 

Syntax of __init__() method is as follows:

 

 

For our Student class, the __init__() method will be as follows:

 

 

__del__() Method (Destructor)

 

The __del__() method is a special method inside a class. It serves as the destructor. It is executed automatically when an object is going to be destroyed. We can explicitly make the __del__() method to execute by deleting an object using del keyword.

 

Syntax of __del__() method is as follows:

 

 

For our Student class, __del__() method can be used as follows:

 

 

Other Special Methods

 

Following are some of the special methods available in Python:

 

Method Description
__repr__() This method returns the string representation of an object. It works on any object, not just user class instances. It can be called as repr(object).
__cmp__() This method can be used to override the behavior of == operator for comparing objects of a class. We can also write our own comparison logic.
__len__() This method is used to retrieve the length of an object. It can be called as len(object).
__call__() This method allows us to make a class behave like a function. Its instance can be called as object(arg1,arg2,…)
__hash__() While working with sets and dictionaries in Python, the objects are stored based on hash value. This value can be generated using this method.
__lt__() This method overrides the behavior of < operator.
__le__() This method overrides the behavior of <= operator.
__eq__() This method overrides the behavior of = operator.
__ne__() This method overrides the behavior of != operator.
__gt__() This method overrides the behavior of > operator.
__ge__() This method overrides the behavior of >= operator.
__iter__() This method can be used to override the behavior of iterating over objects.
__getitem__() This method is used for indexing, i.e., for accessing a value at a specified index.
__setitem__() This method is used to assign an item at a specified index.

 

 

Private Methods

 

Like private variables, we can also created private methods. When there is a need to hide the internal implementation of a class, we can mark the method as private.

 

It is not recommended to access a private method outside the class. But if needed, we can access a private method outside the class as follows:

 

 

If needed, we can access private variables using similar syntax as above.

Following example demonstrates a private method:

 

 

Built-in Functions

 

Following are some of the built-in functions to work with objects:

 

Function Description
hasattr(obj, name) This function checks whether the specified attribute belongs to the object or not.
getattr(obj, name[,default]) This function retrieves the value of the attribute on an object. If the default value is given it returns the that if no attribute is present. Otherwise, this function raises an exception.
setattr(obj, name, value) This function is used to set the value of an attribute on a given object.
delattr(obj, name) This function deletes an attribute on the given object.

 

Built-in Class Attributes

 

Every class in Python by default has some attributes. Those attributes can be accessed using dot (.) operator. These attributes are as follows:

 

Attribute Description
__dict__ Gives the dictionary containing the namespace of a class.
__doc__ Gives the documentation string of the class if specified. Otherwise, it returns None.
__name__ Gives the name of the class
__module__ Gives the name of the module in which the class is defined
__bases__ Gives the base classes in inheritance as a tuple. Otherwise, it returns an empty tuple.

 

Garbage Collection

 

Python runs a process in the background which frees an object from memory when it is no longer needed or if it goes out of scope. This process is known as garbage collection. Python maintains a reference count for each object in the memory.

 

The reference count increases when we create aliases or when we assign an object a new name or place it in a list or other data structure. Reference count decreases when an object goes out of scope and it becomes zero when the object is deleted using del keyword.

 

Class Methods

 

A class method is a method which is marked with classmethod decorator and the first argument to the method is cls. A class method is called using the class name. Class methods are generally used as a factory method to create instances of the class with the specified arguments. Example of a class method is as follows:

 

 

Static Methods

 

A static method is a method marked with staticmethod  decorator. Code that manipulates information or data of a class is placed in a static method. Static method does not depend on the state of the object. Static method can be called using class name. Static method does not have any additional arguments like self and cls.

 

Following example demonstrates a static method:

 

 

 

Related Links:

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up