相关疑难解决方法(0)

继承Python中的实例

在Python中,我想直接从Parent类的实例构造一个Child类的实例.例如:

A = Parent(x, y, z)
B = Child(A)
Run Code Online (Sandbox Code Playgroud)

这是我认为可行的黑客行为:

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)
Run Code Online (Sandbox Code Playgroud)

但是当我跑步的时候

B = Child(A) 
Run Code Online (Sandbox Code Playgroud)

我明白了:

NEW'ING CHILD  
HIJACKING  
NEW'ING CHILD  
RETURNING FROM NEW …
Run Code Online (Sandbox Code Playgroud)

python inheritance overloading instance

11
推荐指数
3
解决办法
7672
查看次数

标签 统计

inheritance ×1

instance ×1

overloading ×1

python ×1