Skip to content

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.

You can create a class in Python using the class 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

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

How to create an object of a class in Python

Section titled “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()

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

Example: Create a class and object in Python

Section titled “Example: Create a class and object in Python”
class.py
class Person:
    pass

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

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

Output:

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

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

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).

  • 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).
  • Instance variables are initialized using the self 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.
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

In the above example, we have created an instance variable named name. We have initialized the name variable to the name parameter of the __init__() method. We have printed the name variable using the person1 and person2 objects. The output shows that the name 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()

Output:

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 name and salary. We have initialized the name and salary variables to the name and salary parameters of the __init__() method. We have printed the name and salary variables using the employee1 and employee2 objects. The output shows that the name and salary variables are unique to the object.

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.

  • 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.
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

In the above example, we have created a class variable named count. We have initialized the count variable to 0. We have incremented the count variable by 1 in the __init__() method. We have printed the count variable using the person1, person2, and Person objects. The output shows that the count variable is shared by all objects of the Person class.

Every python class have the following built-in attributes:

  • __name__: It returns the name of the class.
  • __module__: It returns the name of the module in which the class is defined.
  • __dict__: It returns a dictionary containing the class’s namespace.
  • __doc__: It returns the class documentation string or None if undefined.
  • __bases__: It returns a tuple containing the base classes, in the order of their occurrence in the base class list.
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'>,)

In the above example, we have printed the class attributes. We have used the __name__, __module__, __dict__, __doc__, and __bases__ attributes to print the class attributes.

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.


pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading