Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python类方法不能从类中调用。\u dict___Python_Python 2.7_Oop_Class Method - Fatal编程技术网

python类方法不能从类中调用。\u dict__

python类方法不能从类中调用。\u dict__,python,python-2.7,oop,class-method,Python,Python 2.7,Oop,Class Method,我正在学习python中classmethods的概念 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 在检查类的callable()属

我正在学习python中
classmethods
的概念

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
在检查类的
callable()
属性时,我遇到了一个特殊的输出:

>>> [(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)
即使类
\uu dict\uu
已检查,出于某种原因,类似地
('func_c',False)


有人能解释一下吗?

一个
classmethod
对象不是一个函数对象,不是。它不是用来调用的

classmethod
对象是描述符;描述符有助于将对象绑定到特定实例或类。函数和属性也是描述符;绑定分别生成方法或属性值。看。如果要访问类上的
classmethod
描述符,则会触发
classmethod.\uuuu get\uuuu(None,cls)
调用,该调用生成绑定方法(调用该方法时,调用原始函数,并将类对象作为第一个参数传入)

当您通过
\uuuu dict\uuuu
属性访问所有类属性时,您绕过了描述符协议,因此获得了原始描述符对象本身

访问类上的对象(从而触发
描述符。\uuuuu get\uuuuu(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>>
当然,它本身也是可以调用的


注意,这也适用于
staticmethod
对象;
staticmethod
对象在绑定时只返回原始函数。

由于您似乎是堆栈溢出新手,因此应该阅读。请投票选出有帮助的答案,并接受最好的答案。
>>> A.__dict__['func_c'].__func__
<function func_c at 0x101c59668>