Best way to access an instance of a class 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 ways to access a class method into an instance method.

self.task(10)

      

or

cls = self.__class__
cls.task(20)

      

My question is which one is the best and why?

If both methods are not the same, which one do I use in which condition?

+3


source to share


1 answer


self.task(10)

definitely the best.

First, both instances will eventually complete in the same operation for class instances:

Instances of instances
...
Special attributes: __dict__ - attribute dictionary; __class__ is an instance class



  • calling a class method with a class instance object actually passes the object's class to the method (ref: same chapter in the reference):

... When an instance method object is instantiated by retrieving a class object from a class or instance, its __self__ attribute is the class itself

But the former is simpler and does not require the use of a special attribute.

+2


source







All Articles