python classes and object

Python Classes and Object

Python classes & object are integral parts for designing a python code. A class in python is a user-defined blueprint from which the user can create objects. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by their class) for modifying their state.

Below is an example in python to understand the need of creating a class. Let’s say the user wants to track the number of animals in the family of cats say tiger, cat etc. If user uses a list, the first element could be the cat, while the second element could be tiger. Let’s suppose there are 100 different categories, then how will the user know which element is suppose to be which? What if you wanted to add other categories to this family of cats? This lacks organization and it’s the exact need for classes. 

How to create class in python

  • The user can create a class in python using β€˜Class’ keyword.
  • Attributes are those variables that belong to a class.
  • Attributes are always public and can be access using the dot (.) operator. For example, Myclass.Myattribute


class ClassName:
    # Statement-1
    # Statement-N

Classes & objects in Python

An Object is an instance of a Class in python. A class is like a blueprint while an instance is a copy of the class with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed pug who’s seven years old. You can have many dogs to create many different instances, but without the class as a guide, you would be lost, not knowing what the information is.
An object consists of : 

  • State: The user can denote it by the attributes of an object. It also reflects the properties of an object.
  • Behavior: The user can represent it by the methods of an object. It also reflects the response of an object to other objects.
  • Identity: It gives a unique name to an object and enables one object to interact with other objects.

Below is a program to understand how to use classes & object in Python

class catfamily:
    attribute1 = "Cat"
    attribute2 = "Tiger"
    def fun(self):
        print "I'm a", self.attribute1
        print "I'm a", self.attribute2
rodger = catfamily()


I'm a Cat
I'm a Tiger

Memory Allocation in Python

All data members and member functions of the class can be accessed with the help of objects. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created), memory is allocated. This is the major difference between class & class(object) in python.