简体   繁体   English

如何从 Python 中已有的 class 实例继承?

[英]How to inherit from pre-existing class instance in Python?

I have a class Parent :我有一个 class Parent

class Parent:
    def __init__(self, foo):
        self.foo = foo

I then have another class Child which extends Parent .然后我有另一个 class Child扩展Parent But I want Child to take a pre-existing instance of parent and use this as the parent to inherit from (instead of creating a new instance of Parent with the same constructor parameters).但是我希望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

Then I would ideally be able to do:那么我最好能够做到:

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

print(c.get_foo()) # prints "bar"

You could copy the content of the parents's __dict__ to the child's.您可以将父母的__dict__的内容复制到孩子的。 You can use vars() builtin function to do so, and the dictionary's update() method.您可以使用vars()内置 function 来执行此操作,以及字典的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"

You can use your own constructor - provide a classmethod that takes an instance of a parent.您可以使用自己的构造函数 - 提供一个采用父级实例的类方法。

class Parent:
    def __init__(self, foo):
        self.foo = foo

class Child(Parent):
    def get_foo(self):
        return self.foo

    @classmethod
    def from_parent(cls, parent_instance):
        return cls(parent_instance.foo)


p = Parent('bar')
c = Child.from_parent(p)
c.get_foo()

Using getattr() to fetch the attribute from the parent instance使用getattr()从父实例中获取属性

class Parent: 
    def __init__(self, foo): 
        self.foo = foo 

class Child(Parent): 
    def __init__(self, parent_instance): 
        self.parent_instance = parent_instance
    
    def get_foo(self): 
        return self.foo 
        
    def __getattr__(self, attr):
        return getattr(self.parent_instance, attr)

par = Parent("bar") 
ch = Child(par)
print(ch.get_foo())
#prints bar

I'm not sure inheritance is the right solution here as it breaks the LSP in the __init__ method.我不确定 inheritance 是否是正确的解决方案,因为它破坏了__init__方法中的LSP

Maybe parents and children just share a common interface.也许父母和孩子只是共享一个共同的界面。 I'd prefer something like (python3.8):我更喜欢(python3.8)之类的东西:

from typing import Protocol
    
class FoeAware(Protocol):
    @property
    def foe(self):
        ...
 
class Parent:
    def __init__(self, foe):
        self._foe = foe
   
    @property
    def foe(self):
        return self._foe

class Child:
    def __init__(self, parent: FoeAware):
        self.parent = parent

    @property
    def foe(self):
        return self.parent.foe

p = Parent("bar")
c = Child(p)
c.foe  # bar

The key point is that it takes advantage of polymorphism with a common interface FoeAware , which is preferable to an inheritance tree.关键是它利用了通用接口FoeAware的多态性,这比 inheritance 树更可取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Django 中创建预先存在模型的实例? - How to create an instance of a pre-existing model in django? 如何将预先存在的 python 项目导入 Eclipse? - How do I import a pre-existing python project into Eclipse? 如何使用 Python 在 Selenium 中使用预先存在的条目覆盖特定字段 - How to Overwrite a Specific Field with Pre-existing Entry in Selenium with Python Python:如何向自定义对象添加自定义函数? - Python: How to add a custom function to a pre-existing object? 如何从 SQlAlchemy ORM 会话查询预先存在的表? - How to query pre-existing table from SQlAlchemy ORM session? Append 到 Python 中预先存在的键的值 - Append to value of pre-existing keys in Python 如何重新输入预先存在的 django 应用程序 - How to reenter a pre-existing django app 如何在预先存在的浏览器中运行 Selenium? - How to run Selenium in pre-existing browser? 如何编写 Python 代码来创建一个字典,该字典包含来自一个预先存在的字典的元素,该字典采用一个键和多个值? - How to make Python code that creates a dictionary that contains elements from a pre-existing dictionary that takes one key and many values? 使用Boto连接到预先存在的Windows实例 - Using boto to connect to pre-existing windows instance
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM