1
>>> FooChild = type("FooChild", (Foo,), {"echobar()":echo_bar})
>>> FooChild().echobar()

Traceback (most recent call last):
  File "<pyshell#214>", line 1, in <module>
    FooChild().echobar()
AttributeError: 'FooChild' object has no attribute 'echobar'
>>> FooChild().echobar

Traceback (most recent call last):
  File "<pyshell#215>", line 1, in <module>
    FooChild().echobar
AttributeError: 'FooChild' object has no attribute 'echobar'
>>> hasattr(FooChild, "echobar()")
True
>>> FooChild().echobar()()

Traceback (most recent call last):
  File "<pyshell#217>", line 1, in <module>
    FooChild().echobar()()
AttributeError: 'FooChild' object has no attribute 'echobar'
4

3 回答 3

3

删除这些括号:

FooChild = type("FooChild", (Foo,), {"echobar":echo_bar})

函数名不带括号。附加它们意味着调用函数。如果没有括号,您将获得对函数本身的引用(例如,用于将函数传递给诸如sortor之类的东西map)。

于 2013-11-08T10:56:40.780 回答
2

echobar()在 python 中是一个无效的标识符,所以你不能直接访问它,即使用点语法:

>>> FooChild = type("FooChild", (Foo,), {"echobar()":10})

使用__dict__getattr

>>> FooChild.__dict__['echobar()']
10
>>> getattr(FooChild, 'echobar()')
10

如果您想将其用作属性,则只需去掉括号:

>>> FooChild = type("FooChild", (Foo,), {"echobar":10})
>>> FooChild.echobar
10

如果您想将其用作方法,则:

>>> def echobar(self):return 10

>>> FooChild = type("FooChild", (Foo,), {'echobar':echobar})
>>> FooChild().echobar()
10
于 2013-11-08T11:02:29.403 回答
2

如果您假装echobar()在您的班级中有带有名称的花哨功能,那么访问它的唯一方法是getattr

class Foo(object):pass
echo_bar =lambda *a: 'bar'
FooChild = type("FooChild", (Foo,), {"echobar()":echo_bar})
print getattr(FooChild(), 'echobar()')()
# bar
于 2013-11-08T11:02:42.590 回答