@classmethod in Python Class
@classmethod in Python Class
In Python, a class method is a method that is bound to the class and not the
instance of the class. This means that it operates on the class itself, rather than
on an instance of the class.
A class method is defined using the @classmethod decorator, followed by a
method that takes the class itself as its first argument, conventionally named cls.
When we go to access instance method data use self key-word, but in class
method we use cls key-word in class method
By using class method you can overload instance method __ init __()
In case of class method, there is no need to create an object of class, we cass
access directly like tes = Test.add()
Class variable can be called without creating class object
In [ ]:
1
In [1]:
1 class Test:
2 a = 20
3 b = 30
4 c = 49
5 @classmethod
6 def add(cls): # cls it mean th
7 return cls.a+cls.b
In [2]:
1 obj = Test()
In [3]:
1 obj.a = 30
In [4]:
1 obj.add()
Out[4]:
50
In [5]:
Out[5]:
50
In [ ]:
1
In [6]:
1 class Calculator:
2 def __init__(self, a,b): #ins
3 self.a = a
4 self.b = b
5 def Sub(self): #met
6 return self.a-self.b
7 @classmethod
8 def Sum(cls, a, b): #cla
9 return a+b
10 @classmethod
11 def Mul(cls, a, b): #cla
12 return a*b
In [7]:
Out[7]:
-1
In [8]:
Out[8]:
In [9]:
Out[9]:
30
In [10]:
1 class Company:
2 def __init__(self, product):
3 self.product = product
4 def company_name(self,name):
5 return name
6
In [11]:
1 obj = Company('Laptop')
In [12]:
1 obj.company_name('Lenovo')
Out[12]:
'Lenovo'
In [13]:
1 obj.product
Out[13]:
'Laptop'
In [14]:
In [15]:
1 # product_model('Year')
In [16]:
In [17]:
1 Company.product_model('XFGRT-5689')
In [ ]:
1
In [ ]:
1
In [18]:
In [19]:
--------------------------------------------------------
-------------------
TypeError Traceback (mos
t recent call last)
~\AppData\Local\Temp\ipykernel_12336\441683511.py in <mo
dule>
----> 1 battery_capacity('2 pc') # call funct
ion
In [20]:
1 Company.battery_capacity = classmethod(battery_capacity)
In [21]:
1 Company.battery_capacity(['GH-45','YU-89'])
In [ ]:
1
del key-word
delattr(class_name, 'class_method') # class method will use as string
In [22]:
1 obj = Company('HP')
In [23]:
1 obj.product
Out[23]:
'HP'
In [24]:
1 Company.product_model('HGTY-5896')
In [25]:
In [26]:
--------------------------------------------------------
-------------------
AttributeError Traceback (mos
t recent call last)
~\AppData\Local\Temp\ipykernel_12336\3874234762.py in <m
odule>
----> 1 Company.product_model('HGTY-5896')
# class method does not exist
In [ ]:
1
In [27]:
1 Company.battery_capacity('2 PC')
Number of battery is : 2 PC
In [28]:
1 delattr(Company, 'battery_capacity')
In [29]:
1 Company.battery_capacity('2 PC')
--------------------------------------------------------
-------------------
AttributeError Traceback (mos
t recent call last)
~\AppData\Local\Temp\ipykernel_12336\2424357768.py in <m
odule>
----> 1 Company.battery_capacity('2 PC')
In [ ]:
1
In [30]:
In [ ]:
In [ ]:
1