>>> 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'
答案 0 :(得分:3)
删除这些括号:
FooChild = type("FooChild", (Foo,), {"echobar":echo_bar})
函数的名称没有括号。附加它们意味着调用该函数。如果没有括号,您可以参考函数本身(例如,将函数传递给sort
或map
)。
答案 1 :(得分:2)
echobar()
是python中的invalid identifier,因此您无法直接访问它,即使用点语法:
>>> 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
答案 2 :(得分:2)
如果您假装在您的班级中使用名称为echobar()
的花哨功能,则只有getattr
才能访问它:
class Foo(object):pass
echo_bar =lambda *a: 'bar'
FooChild = type("FooChild", (Foo,), {"echobar()":echo_bar})
print getattr(FooChild(), 'echobar()')()
# bar