在python中,如果我编辑它:type(“myclass”,(foo,),{“bar()”,barbar},我如何访问属性“bar()”

时间:2013-11-08 10:53:28

标签: python class attributes

>>> 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'

3 个答案:

答案 0 :(得分:3)

删除这些括号:

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

函数的名称没有括号。附加它们意味着调用该函数。如果没有括号,您可以参考函数本身(例如,将函数传递给sortmap)。

答案 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