指向方法的类变量的行为不同于

2024-09-17 19:43:48 发布

您现在位置: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)

Tags: 方法instanceinpymainusrdefline
2条回答

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

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()时,应该传递实例

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

#!/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()

相关问题 更多 >