Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 277
Kallz Avatar asked Jul 18 '17 17:07

Kallz


People also ask

Can instance methods access class methods?

Instance methods can access class variables and class methods directly. Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference.

Which is the correct way to access the current instance of the class from its method?

There are two ways to access the instance variable of class: Within the class by using self and object reference. Using getattr() method.

Can you call a class method from an instance?

A class method is a method that's shared among all objects. To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself. All of these use the same method.


1 Answers

self.task(10) is definitely the best.

First, both will ultimately end in same operation for class instances:

  • __class__ is a special attribute that is guaranteed to exist for an class instance object and is is the class of the object (Ref: Python reference manual / Data model / The standard type hierarchy)

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.

like image 121
Serge Ballesta Avatar answered Sep 23 '22 09:09

Serge Ballesta