Class and Objects in Python
In the previous guide, we discussed Object-oriented programming in Python. In this tutorial, we will see how to create classes and objects in Python.
Define class in Python
A class is defined using the keyword class.
Example
In this example, we are creating an empty class DemoClass. This class has no attributes and methods.
The string that we mention in the triple quotes is a docstring which is an optional string that briefly explains the purpose of the class.
class DemoClass:
"""This is my docstring, this explains brief about the class"""
# this prints the docstring of the class
print(DemoClass.__doc__)
Output
This is my docstring, this explains brief about the class
Creating Objects of class
In this example, we have a class MyNewClass that has an attribute num and a function hello(). We are creating an object obj of the class and accessing the attribute value of object and calling the method hello() using the object.
class MyNewClass:
"""This class demonstrates the creation of objects"""
# instance attribute
num = 100
# instance method
def hello(self):
print("Hello World!")
# creating object of MyNewClass
obj = MyNewClass()
# prints attribute value
print(obj.num)
# calling method hello()
obj.hello()
# prints docstring
print(MyNewClass.__doc__)
Output
100
Hello World!
This class demonstrates the creation of objects
Leave Comment