Search code examples
pythonpython-2.7python-3.xclass-method

Best way to access class-method into instance method


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?


Solution

  • 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

    • calling a classmethod with a class instance object actually pass the class of the object to the method (Ref: same chapter of ref. manual):

    ...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.