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 class
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 ClassName:
pass
class ClassName:
pass
In the above example, we have created a class named ClassName
ClassName
. The class body is empty. We have used the pass
pass
keyword to avoid getting an error. The pass
pass
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 ClassName:
pass
object_name = ClassName()
class ClassName:
pass
object_name = ClassName()
In the above example, we have created an object of the ClassName
ClassName
class. We have assigned the object to the object_name
object_name
variable.
Example: Create a class and object in Python
class Person:
pass
class Person:
pass
In the above example, we have created a class named Person
Person
. The class body is empty. We have used the pass
pass
keyword to avoid getting an error. The pass
pass
keyword is used as a placeholder for future code.
class Person:
pass
person = Person()
print(person)
class Person:
pass
person = Person()
print(person)
Output:
C:\Users\username>python class.py
<__main__.Person object at 0x0000020E7F7F4F70>
C:\Users\username>python class.py
<__main__.Person object at 0x0000020E7F7F4F70>
In the above example, we have created an object of the Person
Person
class. We have assigned the object to the person
person
variable. We have printed the person
person
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
self
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.
Example: Instance variables in Python
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 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:
C:\Users\username>python class.py
John
Bob
C:\Users\username>python class.py
John
Bob
In the above example, we have created an instance variable named name
name
. We have initialized the name
name
variable to the name
name
parameter of the __init__()
__init__()
method. We have printed the name
name
variable using the person1
person1
and person2
person2
objects. The output shows that the name
name
variable is unique to the object.
Another example of instance variables:
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 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:
C:\Users\username>python class.py
Name: John
Salary: 10000
Name: Bob
Salary: 20000
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
name
and salary
salary
. We have initialized the name
name
and salary
salary
variables to the name
name
and salary
salary
parameters of the __init__()
__init__()
method. We have printed the name
name
and salary
salary
variables using the employee1
employee1
and employee2
employee2
objects. The output shows that the name
name
and salary
salary
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 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 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:
C:\Users\username>python class.py
2
2
2
C:\Users\username>python class.py
2
2
2
In the above example, we have created a class variable named count
count
. We have initialized the count
count
variable to 0
0
. We have incremented the count
count
variable by 1
1
in the __init__()
__init__()
method. We have printed the count
count
variable using the person1
person1
, person2
person2
, and Person
Person
objects. The output shows that the count
count
variable is shared by all objects of the Person
Person
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 orNone
None
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 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 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:
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'>,)
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