Python class methods cannot be called from .__ dict__ class

I am learning a concept classmethodsin python.

class A():
    n=0
    # object method
    def func_o(self):
        self.n += 1
        print self.n

    # well, class method
    @classmethod
    def func_c(cls):
        cls.n += 1
        print cls.n

when checking callable()class attributes , I came across this peculiar result:

>>> [(k, callable(v)) for k,v in A.__dict__.items()]
[('__module__', False), ('__doc__', False), ('func_o', True), ('func_c', False), ('n', False)] 

('func_o', True)although the class has __dict__been tested, similarly ('func_c', False)for some reason.

Can someone explain?

+4
source share
1 answer

An object is classmethodnot an object of a function, no. It is not intended to be called.

classmethod ; . ; , . . Python . classmethod , classmethod.__get__(None, cls), ( , ).

__dict__, , .

( descriptor.__get__(None, cls), ), classmethod:

>>> A.__dict__['func_c']
<classmethod object at 0x1018e6cc8>
>>> A.__dict__['func_c'].__get__(None, A)  # explicitly bind to a class
<bound method classobj.func_c of <class __main__.A at 0x101c52328>>
>>> callable(A.__dict__['func_c'].__get__(None, A))
True
>>> A.func_c    # trigger the protocol and bind to a class
<bound method classobj.func_c of <class __main__.A at 0x101c52328>>

, classmethod, __func__:

>>> A.__dict__['func_c'].__func__
<function func_c at 0x101c59668>

, , .

, staticmethod; a staticmethod , , .

+5

Source: https://habr.com/ru/post/1667007/


All Articles