Skip to content

Class in Python

Class in Python

In object-oriented programming (OOP), a class is a blueprint or template for creating objects. It defines a set of attributes (data members) and methods (functions) that characterize any object instantiated from that class. A class encapsulates the common properties and behaviors that its objects share. It serves as a blueprint for creating instances or objects, providing a way to model and organize code in a modular and reusable fashion.

How to create a class in Python

You can create a class in Python using the classclass keyword followed by the name of the class and a colon ::. The class body is indented and contains class attributes (data members) and methods (functions).

Syntax:

class.py
class ClassName:
    pass
class.py
class ClassName:
    pass

In the above example, we have created a class named ClassNameClassName. The class body is empty. We have used the passpass keyword to avoid getting an error. The passpass keyword is used as a placeholder for future code.

How to create an object of a class in Python

You can create an object of a class in Python using the class name followed by parentheses ()().

Syntax:

class.py
class ClassName:
    pass
 
object_name = ClassName()
class.py
class ClassName:
    pass
 
object_name = ClassName()

In the above example, we have created an object of the ClassNameClassName class. We have assigned the object to the object_nameobject_name variable.

Example: Create a class and object in Python

class.py
class Person:
    pass
class.py
class Person:
    pass

In the above example, we have created a class named PersonPerson. The class body is empty. We have used the passpass keyword to avoid getting an error. The passpass keyword is used as a placeholder for future code.

class.py
class Person:
    pass
 
person = Person()
print(person)
class.py
class Person:
    pass
 
person = Person()
print(person)

Output:

command
C:\Users\username>python class.py
<__main__.Person object at 0x0000020E7F7F4F70>
command
C:\Users\username>python class.py
<__main__.Person object at 0x0000020E7F7F4F70>

In the above example, we have created an object of the PersonPerson class. We have assigned the object to the personperson variable. We have printed the personperson variable. The output shows the memory address of the object.

Instance Variables

In Python, an instance variable is a variable that is defined inside a method and belongs only to the current instance of a class. Instance variables are not shared by all instances of a class. Each instance variable is unique to the object. They are defined inside the constructor method __init__(self)__init__(self).

Properties of instance variables:

  • Instance variables are owned by objects of the class.
  • Instance variables are not shared by all objects of the class. Each object has its own copy of the instance variable.
  • Instance variables are defined inside the constructor method __init__(self)__init__(self).
  • Instance variables are initialized using the selfself keyword.
  • Instance variables can be accessed using the dot .. operator with the object.
  • Instance variables can be accessed outside the class using the object name.

Example: Instance variables in Python

class.py
class Person:
    '''This is a Person class'''
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print('Hello, my name is', self.name)
 
person1 = Person('John')
person2 = Person('Bob')
print(person1.name)
print(person2.name)
class.py
class Person:
    '''This is a Person class'''
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print('Hello, my name is', self.name)
 
person1 = Person('John')
person2 = Person('Bob')
print(person1.name)
print(person2.name)

Output:

command
C:\Users\username>python class.py
John
Bob
command
C:\Users\username>python class.py
John
Bob

In the above example, we have created an instance variable named namename. We have initialized the namename variable to the namename parameter of the __init__()__init__() method. We have printed the namename variable using the person1person1 and person2person2 objects. The output shows that the namename variable is unique to the object.

Another example of instance variables:

class.py
class Employee:
    '''This is an Employee class'''
    name # Optional
    salary # Optional
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
    def display(self):
        print('Name:', self.name)
        print('Salary:', self.salary)
 
employee1 = Employee('John', 10000)
employee2 = Employee('Bob', 20000)
employee1.display()
employee2.display()
class.py
class Employee:
    '''This is an Employee class'''
    name # Optional
    salary # Optional
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
    def display(self):
        print('Name:', self.name)
        print('Salary:', self.salary)
 
employee1 = Employee('John', 10000)
employee2 = Employee('Bob', 20000)
employee1.display()
employee2.display()

Output:

command
C:\Users\username>python class.py
Name: John
Salary: 10000
Name: Bob
Salary: 20000
command
C:\Users\username>python class.py
Name: John
Salary: 10000
Name: Bob
Salary: 20000

In the above example, we have created two instance variables named namename and salarysalary. We have initialized the namename and salarysalary variables to the namename and salarysalary parameters of the __init__()__init__() method. We have printed the namename and salarysalary variables using the employee1employee1 and employee2employee2 objects. The output shows that the namename and salarysalary variables are unique to the object.

Class Variables

In Python, a class variable is a variable that is shared by all objects of a class. Class variables are defined within the class construction. Because class variables are owned by the class itself, they are shared by all instances of the class. They therefore will generally have the same value for every instance unless you are using the class variable to initialize a variable.

Properties of class variables:

  • Class variables are owned by the class itself.
  • Class variables are shared by all objects of the class.
  • Class variables are defined within the class construction.
  • Class variables are initialized using the class name.
  • Class variables can be accessed using the dot .. operator with the class name.
  • Class variables can be accessed outside the class using the class name.
  • Class variables can be accessed outside the class using the object name.

Example: Class variables in Python

class.py
class Person:
    '''This is a Person class'''
    count = 0
    def __init__(self, name):
        self.name = name
        Person.count += 1
    def say_hi(self):
        print('Hello, my name is', self.name)
 
person1 = Person('John')
person2 = Person('Bob')
print(person1.count)
print(person2.count)
print(Person.count)
class.py
class Person:
    '''This is a Person class'''
    count = 0
    def __init__(self, name):
        self.name = name
        Person.count += 1
    def say_hi(self):
        print('Hello, my name is', self.name)
 
person1 = Person('John')
person2 = Person('Bob')
print(person1.count)
print(person2.count)
print(Person.count)

Output:

command
C:\Users\username>python class.py
2
2
2
command
C:\Users\username>python class.py
2
2
2

In the above example, we have created a class variable named countcount. We have initialized the countcount variable to 00. We have incremented the countcount variable by 11 in the __init__()__init__() method. We have printed the countcount variable using the person1person1, person2person2, and PersonPerson objects. The output shows that the countcount variable is shared by all objects of the PersonPerson class.

Class attributes

Every python class have the following built-in attributes:

  • __name____name__: It returns the name of the class.
  • __module____module__: It returns the name of the module in which the class is defined.
  • __dict____dict__: It returns a dictionary containing the class’s namespace.
  • __doc____doc__: It returns the class documentation string or NoneNone if undefined.
  • __bases____bases__: It returns a tuple containing the base classes, in the order of their occurrence in the base class list.

Example: Class attributes in Python

class.py
class Person:
    '''This is a Person class'''
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print('Hello, my name is', self.name)
 
print(Person.__name__)
print(Person.__module__)
print(Person.__dict__)
print(Person.__doc__)
print(Person.__bases__)
class.py
class Person:
    '''This is a Person class'''
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print('Hello, my name is', self.name)
 
print(Person.__name__)
print(Person.__module__)
print(Person.__dict__)
print(Person.__doc__)
print(Person.__bases__)

Output:

command
C:\Users\username>python class.py
Person
__main__
{'__module__': '__main__', '__doc__': 'This is a Person class', '__init__': <function Person.__init__ at 0x0000020E7F7F1CA0>, 'say_hi': <function Person.say_hi at 0x0000020E7F7F1D30>}
This is a Person class
(<class 'object'>,)
command
C:\Users\username>python class.py
Person
__main__
{'__module__': '__main__', '__doc__': 'This is a Person class', '__init__': <function Person.__init__ at 0x0000020E7F7F1CA0>, 'say_hi': <function Person.say_hi at 0x0000020E7F7F1D30>}
This is a Person class
(<class 'object'>,)

In the above example, we have printed the class attributes. We have used the __name____name__, __module____module__, __dict____dict__, __doc____doc__, and __bases____bases__ attributes to print the class attributes.

Conclusion

In this tutorial, you learned about class in Python. You learned how to create a class in Python. You learned how to create an object of a class in Python. You learned about instance variables and class variables. You learned about class attributes. You also learned how to read the docstring of a class. Now you can create a class and object in Python. You can also create instance variables and class variables in Python. You can also read the docstring of a class in Python. For more information, visit the Python Classes and Objects documentation page. For more tutorials, visit our Python Central Hub.

Was this page helpful?

Let us know how we did