Best way to access class-method into instance method
Asked Answered
B

1

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?

Bootie answered 18/7, 2017 at 17:35 Comment(5)
You can also just directly call Test.task(20) from within that method, instead of your two-liner.Lacagnia
@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).Cohe
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.Irritation
wouldnt it be the first one considering that self.__class__ would create an object while the first one is a direct call?Madeup
@Lacagnia 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 methodBootie
V
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.

Vitamin answered 19/7, 2017 at 12:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.