在 Python 中,我想直接从 Parent 类的实例构造 Child 类的实例。例如:
A = Parent(x, y, z)
B = Child(A)
这是一个我认为可能有用的hack:
class Parent(object):
def __init__(self, x, y, z):
print "INITILIZING PARENT"
self.x = x
self.y = y
self.z = z
class Child(Parent):
def __new__(cls, *args, **kwds):
print "NEW'ING CHILD"
if len(args) == 1 and str(type(args[0])) == "<class '__main__.Parent'>":
new_args = []
new_args.extend([args[0].x, args[0].y, args[0].z])
print "HIJACKING"
return Child(*new_args)
print "RETURNING FROM NEW IN CHILD"
return object.__new__(cls, *args, **kwds)
但是当我跑步时
B = Child(A)
我得到:
NEW'ING CHILD
HIJACKING
NEW'ING CHILD
RETURNING FROM NEW IN CHILD
INITILIZING PARENT
Traceback (most recent call last):
File "classes.py", line 52, in <module>
B = Child(A)
TypeError: __init__() takes exactly 4 arguments (2 given)
看起来黑客就像我预期的那样工作,但编译器最后会抛出一个 TypeError 。我想知道是否可以重载 TypeError 以使其忽略 B = Child(A) 习语,但我不知道该怎么做。无论如何,请您给我您从实例继承的解决方案吗?
谢谢!