Class and Object
Here, you will find more about python class and object.
As python is an object-oriented language, it considers everything as an object. Class is used to bind data and functionality together. The class can contain class variables, data, functions, objects, etc.
Create a class:
‘class’ keyword is used to create a class. Define the name of the class followed by ‘:’
Below is an example of a simple python class. Here we have defined a class called ‘Bonus’ and defined a function as ‘calculate_bonus’ to calculate the ‘bonus’ of an employee based on salary.
class Bonus: def __init__(self): self.profit_per = 0.1 def calculate_bonus(self,salary): total_amount = salary + salary * self.profit_per return total_amount
To create an object of the class and use the function using below syntax.
bonus = Bonus() print("Bonus amount",bonus.calculate_bonus(1000))
-Here ‘bonus’ is an object of the class ‘Bonus’
-‘__init__’ is called as ‘constructor’ and a special method in python. This is initialized when an object of the class is created. The block of the inside __init__ method will execute first before any other execution.
– ‘self’ keyword is used to identify the variable as a class instance variable and this is unique to each instance. ‘self’ variable is different from the ‘global’ variable. We will discuss ‘self’ in detail in the later section.
More about Class and instance variable:
The following example has both class and instance variables defined.
class Bike: global_brand = 'hd' ## class variable def __init__(self,brand,cost): self.brand = brand ## instance variable self.cost = cost
bike1= Bike('hero',100000) print("Printing class variable-", bike1.brand) print("Printing instance variable-", bike1.global_brand)
Output:
Printing class variable- hero
Printing instance variable- hd
bike2 = Bike('hero2',100000) print("Printing class variable-", bike2.brand) print("Printing instance variable-", bike2.global_brand)
Output:
Printing class variable- hero2
Printing instance variable- hd
Notice that the ‘global_brand’ variable is shared with both the object whereas the ‘brand’ variable is unique with each object.
Delete an object:
The object can be deleted by using the ‘del’ keyword. This will free up memory.
del bonus
Python will through an error when trying to access objects after deletion.
print("Bonus amount",bonus.calculate_bonus(1000))
Traceback (most recent call last):
File "/Users/test/classtest.py", line 15, in
print("Bonus amount",bonus.calculate_bonus(1000))
NameError: name 'bonus' is not defined
Conclusion:
In this blog, you have learned about the python class and object. Try creating more classes with instance and class variables to understand more.