指向方法的类变量表现不同

时间:2015-01-12 14:31:08

标签: python

类变量的行为与常规变量不同。当调用类变量作为方法时,它不会被调用,就好像它只是一个常规变量:

#!/usr/bin/env python
def func():
    print 'func called'

class MyClass(object):
    FUNC = func

    def call_func(self):
        MyClass.FUNC()

instance = MyClass()
instance.call_func()

产地:

Traceback (most recent call last):
  File "main.py", line 12, in <module>
    instance.call_func()
  File "main.py", line 9, in call_func
    MyClass.FUNC()
TypeError: unbound method func() must be called with MyClass instance as first argument (got nothing instead)

2 个答案:

答案 0 :(得分:2)

为了使其按预期工作,您必须使用FUNC装饰staticmethod()

#!/usr/bin/env python
def func():
    print 'func called'

class MyClass(object):
    FUNC = staticmethod(func)

    def call_func(self):
        MyClass.FUNC()

instance = MyClass()
instance.call_func()

答案 1 :(得分:0)

在我看来,这是一个非常直接的解决方案:

def func():
    print 'func called'

class MyClass(object):
    def FUNC(self):
        return func()

    def call_func(self):
        MyClass.FUNC(self)

instance = MyClass()
instance.call_func()

不同之处在于,当您致电MyClass.FUNC()时,您应该传递实例。