8
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?

5
  • 5
    You can also just directly call Test.task(20) from within that method, instead of your two-liner. Commented Jul 18, 2017 at 17:39
  • 3
    @xgord: yes but the two are not equivalent. Task.task(20) will always call the task defined in Task whereas a subclass can override the method. In that case self.task(20) in a SubTask class will access SubTask.task(20). Commented Jul 18, 2017 at 17:42
  • 1
    That depends on the intended use - self will 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 setting your_instance.task = some_dynamic_override and then self.task() will be calling that function. Commented Jul 18, 2017 at 17:44
  • wouldnt it be the first one considering that self.__class__ would create an object while the first one is a direct call? Commented Jul 18, 2017 at 17:46
  • @xgord I want to know that both ways are same or not, if not then what is differences and when I use first type or second method Commented Jul 19, 2017 at 7:01

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.