Role of Instance, Class, Static Methods in Python✌
Instance Methods
Instance methods are most widely used methods. It receives the instance of the class as the first argument, which by convention is called self
, and points to the instance of our class . However it can take any number of arguments.
Using the self
parameter, we can access the other attributes and methods on the same object and can change the object state. Also, using the self.__class__
attribute, we can access the class attributes, and can change the class state as well. Therefore, instance methods gives us control of changing the object as well as the class state.
Class Methods
Class methods are created using the @classmethod decorator.
A class method accepts the class as an argument to it which by convention is called cls
. This stands for class, and like self, gets automatically passed in by Python.
Class methods don't need self as an argument, but they do need a parameter called cls. It take the cls
parameter, which points to the class defined in the program instead of the object of it. It is declared with the @classmethod
decorator.
@classmethod
for sub-classes as well.Static Methods
@staticmethod
decorator to flag it as static. It does not receive an implicit first argument (neither self
nor cls
).It can also be put as a method that “does’t know its class”.
Hence a static method is merely attached for convenience to the class object. Hence static methods can neither modify the object state nor class state. They are primarily a way to namespace our methods.
Pass members from one class to other
In PYTHON we can pass data members even without concept of inheritance.
It can also use child parent concept to access members and methods of one class into another which is known as inheritance.
def __init__(self,name,age):
self.name = name
self.age = age
def printage(self):
print('student age is',self.age)
def changeage(x):
x.age = x.age+2
x.printage()
Demo.changeage(stud1)
student age is 25
Comments
Post a Comment