class Test(object):
def __init__(self):
pass
def testmethod(self):
# instance method
self.task(10) # type-1 access class method
cls = self.__class__
cls.task(20) # type-2 access class method
@classmethod
def task(cls,val)
print(val)
I have two way to access class method into instance method.
self.task(10)
or
cls = self.__class__
cls.task(20)
My question is which one is the best and why??
If both ways are not same, then which one I use in which condition?
Instance methods can access class variables and class methods directly. Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference.
There are two ways to access the instance variable of class: Within the class by using self and object reference. Using getattr() method.
A class method is a method that's shared among all objects. To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself. All of these use the same method.
self.task(10)
is definitely the best.
First, both will ultimately end in same operation for class instances:
Class instances
...
Special attributes: __dict__ is the attribute dictionary; __class__ is the instance’s class
...When an instance method object is created by retrieving a class method object from a class or instance, its __self__ attribute is the class itself
But the first is simpler and does not require usage of a special attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With