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?
Test.task(20)from within that method, instead of your two-liner.Task.task(20)will always call thetaskdefined inTaskwhereas a subclass can override the method. In that caseself.task(20)in aSubTaskclass will accessSubTask.task(20).selfwill always refer to the current instances' methods and will persist not only through the inheritance chain (compared to calling by a class name, i.e.Test.task()), picking up the latest override, even a dynamic one, while referring by class type will always point to the actual class method. Nothing stops you from settingyour_instance.task = some_dynamic_overrideand thenself.task()will be calling that function.