如何从Python中预先存在的类实例继承?

Jon*_*lon 5 python oop inheritance python-3.x

我有一堂课Parent

class Parent:
    def __init__(self, foo):
        self.foo = foo
Run Code Online (Sandbox Code Playgroud)

然后我有另一个Child扩展的类Parent。但我想Child获取一个预先存在的实例parent并将其用作要继承的父实例(而不是创建Parent具有相同构造函数参数的新实例)。

class Child(Parent):
    def __init__(self, parent_instance):
        """ Do something with parent_instance to set this as the parent instance """

    def get_foo(self):
        return self.foo
Run Code Online (Sandbox Code Playgroud)

然后我理想地能够做到:

p = Parent("bar")
c = Child(p)

print(c.get_foo()) # prints "bar"
Run Code Online (Sandbox Code Playgroud)

rev*_*ano 7

您可以将父母的内容复制__dict__到孩子的内容。您可以使用vars()内置函数和字典的update()方法来执行此操作。

class Child(Parent):
    def __init__(self, parent_instance):
        vars(self).update(vars(parent_instance))

    def get_foo(self):
        return self.foo


p = Parent("bar")
c = Child(p)

print(c.get_foo())
# prints "bar"
Run Code Online (Sandbox Code Playgroud)