Python being an object oriented programming language works on the concept of creating classes and using objects of the class to access the properties and methods defined by the class.
What is a class
In object oriented programming class defines a new type. Class encapsulates data (variables) and functionality (methods) together. Once a class is defined it can be instantiated to create objects of that class. Each class instance (object) gets its own copy of attributes for maintaining its state and methods for modifying its state.
You can create multiple class instances, they all will be of the same type (as defined by the class) but they will have their own state i.e. different values for attributes.
Class in Python
A class in Python is created using the keyword class followed by the class name.
Syntax of class creation in Python is as follows-
class Classname(baseclass): '''doc string describing what the class is about''' class variable def __init__(self): def method1(self): def method2(self)
In Python if class is not explicitly inheriting from a base class still it derives from ‘object’ class so explicitly or implicitly all classes inherit from object class. If your class is not inheriting from any other class then you don’t need to explicitly write object class in parenthesis as that is implied.
So both of the following class definitions are equivalent.
class Classname(object): and class Classname:
Doc string is also optional and used to provide information about the class and the functionality it provides.
If you have any class variables that are shared by the class instances those are defined outside any methods.
__init__() is a special function that is called automatically when an object of the class is created. It acts a constructor of the class and used to initialize an object.
- Refer this post Constructor in Python - __init__() function to know more about __init__().
- Refer this post self in Python to know more about self variable in Python.
Python class creation example
Here is an example of creating a class in Python.
class Person: '''Class Person displaying person information''' def __init__(self, name, age): self.name = name self.age = age def display(self): print(self.name) print(self.age)
Class is defined using keyword class and the name of the class is ‘Person’. As already stated since this class is not deriving from any other base class so by default it inherits from class ‘object’.
Person class has two variables name and age and a method display that displays the value of those attributes.
__init__() special method for initializing the object when it is created is also defined.
Now we have the blueprint ready what we need is to create objects of the class to access those attributes of the class.
Creating object in Python
Syntax for creating an object in Python is as follows.
obj = Classname()
Here is an updated version of Person class to understand how to create objects of a class and how objects are initialized. There is also a class variable person_total which is shared among all the class instances.
class Person: '''Class Person displaying person information''' #class variable person_total = 0 def __init__(self, name, age): print('init called') self.name = name self.age = age Person.person_total +=1 def display(self): print(self.name) print(self.age) # printing doc string print(Person.__doc__) # creating class instances person1 = Person('John', 40) person1.display() person2 = Person('Lila', 32) person2.display() print('Count- ', Person.person_total)
Output
Class Person displaying person information init called John 40 init called Lila 32 Count- 2
In the example object of the class is created using the following statement-
person1 = Person('John', 40) #creates another object person2 = Person('Lila', 32)
While creating object you pass the values for the variables, Python calls the __init__() method automatically when object is created to initialize the object.
To call any method syntax is- object.methodname()
Class variable belongs to the class rather than to any particular instance of the class so class variable is accessed using Classname itself.
Person.person_total
Special class attributes in Python
In the above example print(Person.__doc__) prints the doc string. If you are wondering from where does this attribute __doc__ come from then please note that it is a built in class attribute. Every class in Python has some built-in class attributes that provides information about the class.
- __name__ : Gives the class name.
- __module__ : Gives the module name in which the class was defined.
- __dict__ : A dictionary containing the class’s namespace.
- __bases__ : A tuple containing the base classes, in the order of their occurrence in the base class list.
- __doc__ : Gives the class’s documentation string, or None if undefined.
class Person: '''Class Person displaying person information''' #class variable person_total = 0 def __init__(self, name, age): print('init called') self.name = name self.age = age Person.person_total +=1 def display(self): print(self.name) print(self.age) # printing class attributes print('__bases__ attribute-', Person.__bases__) print('__dict__attribute-',Person.__dict__) print('__doc__attribute-',Person.__doc__) print('__name__attribute-',Person.__name__) print('__module__attribute-',Person.__module__)
Output
__bases__ attribute- (<class 'object'>,) __dict__attribute- {'__module__': '__main__', '__doc__': 'Class Person displaying person information', 'person_total': 0, '__init__': <function Person.__init__ at 0x000001D9598D2EA0>, 'display': <function Person.display at 0x000001D9598EB268>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>} __doc__attribute- Class Person displaying person information __name__attribute- Person __module__attribute- __main__
That's all for this topic Class And Object in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-
Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man python tutorial
ReplyDeleteThanks so much for this, its very helpful!
ReplyDelete