如何“反实例化”对象?
我写了一个Python函数:
def instantiate(c):
if inspect.isclass(c): return c()
elif isinstance(c, object): return c
else: raise Exception, '%s is not an object or class.' % c
现在我想做相反的事情:从一个已经创建好的对象中获取它的类,这样我就可以用不同的参数重新创建它。请问我该怎么做?
测试:
>>> f = Form()
>>> type(f)()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: instance() takes at least 1 argument (0 given)
>>> f.__class__()
<forms.Form instance at 0xb7f4d5cc>
更多测试:
>>> o = object()
>>> type(o)()
<object object at 0xb7f78478>
>>> o.__class__()
<object object at 0xb7f78480>
看起来对object
有效,但对我的Form
类不行:
class Form:
def __init__(self, data={}, prefix='', action='', id=None):
我猜这和self
有关,但我不知道具体是什么。
2 个回答
3
要获取x的类
x.__class__
2
对象 c
的类型是 type(c)
。