Python: 绕开 __init__


某些时候我们需要绕开初始化函数来创建对象,比如做反序列化。
>>> class A(object):
...     def __init__(self, x, y):
...         print "init", x, y
...         self.x = x
...         self.y = y
...     def test(self):
...         print "test:", self.x, self.y
...    

>>> class _Empty(object): pass
...

>>> o = _Empty()
>>> o.__class__ = A
>>> o.x = 1
>>> o.y = 2
>>> o.test()
test: 1 2

>>> type(o)
<class __main__.A>

>>> isinstance(o, A)
True

对于 classic class,我们还可以直接用 types.instance(),这样更简单一些。
>>> class A:
...     def __init__(self, x, y):
...         print "init:", x, y
...         self.x = x
...         self.y = y
...     def test(self):
...         print "test:", self.x, self.y
...         

>>> import types
>>> a1 = types.InstanceType(A, dict(x = 1, y = 2))
>>> a1.test()
test: 1 2
>>> a1.__class__
<class __main__.A at 0x1025869b0>

>>> class _Empty: pass
... 
>>> a2 = _Empty()
>>> a2.__class__ = A
>>> a2.x = 1
>>> a2.y = 2
>>> a2.test()
test: 1 2

可见 Python 的对象区别在于 __class__、__bases__ 和 __dict__ 这些,其他的好说。

顺便提一下 types module,我们也许还会用到下面这样的 "动态" 编程方式。
>>> import sys, types

>>> sys.modules["X"] = types.ModuleType("X", "test module")

>>> import X
>>> X.__doc__
test module

相关内容

    暂无相关文章

评论关闭