There are three types of methods in classes, we'll check them out below.
classmethod
as decoration (using @classmethod
prefix). These methods should have class as their first parameter, which can be of any name, CLS is preferred. This parameter further can be used to access other class variables/methods inside the current method.class MyClass:
# Class variables: They are outside of any methods
my_var1 = 20
my_var2 = 10
# Defining a class method, use the '@classmethod' decorator
@classmethod
def fun1(CLS):
# Notice: The 'CLS' parameter
print("This is a class method")
# access the class variable using 'CLS' parameter
print(CLS.my_var2)
## Accessing variables/methods using class
print(MyClass.my_var1) # 20
MyClass.fun1() # This is a class method \
# 10
# Modify the class variable, will reflect to class
# and all of its instances
MyClass.my_var1 = 42
## Access using instance
my_instance = MyClass()
print(my_instance.my_var1) # 42
my_instance.fun1() # This is a class method \
# 10
## Optionally creating new class variables using the class
MyClass.new_var = 43
print(MyClass.new_var) # 43
class MyClass:
my_var1 = 10
# Defining instance methods
def __init__(self):
# Define instance variables in the constructor method
# with 'self.' prefix
self.other_var1 = 30
self.other_var2 = 40
# can also access class variables
print(self.my_var1)
# defining another instance method
def fun1(self):
# Notice: The 'self' parameter
print("This is a instance method")
## Accessing variables/methods using class
# Note: Comment line number 21 & 22 to continue further execution
print(MyClass.my_var1) # 10
print(MyClass.other_var1) # AttributeError
MyClass.fun1() # AttributeError
## Access using instance
my_instance = MyClass() # 10
print(my_instance.other_var1) # 30
my_instance.fun1() # This is a instance method
## Optionally creating instance variables using the instance
my_instance.new_var = 42
print(my_instance.new_var) # 42
staticmethod
as decoration (using @staticmethod
prefix), these methods are not required to pass CLS/self as first argument. Lastly, these methods can also be subclassed.class MyClass:
# Defining a class method: Use the '@staticmethod' decorator
@staticmethod
def fun3():
# Can't access any instance's/class's variable/methods
# but can do its own task
print("This is static method")
## Access using class
MyClass.fun3() # This is static method
## Access using instance
my_instance = MyClass()
my_instance.fun3() # This is static method