您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将对象转换为Python中的子类?

将对象转换为Python中的子类?

由于库函数返回A,因此如果不更改它就不能使其返回B。

您可以做的一件事是编写一个函数,以获取A实例的字段并将其复制到新的B实例中:

class A: # defined by the library
    def __init__(self, field):
        self.field = field

class B(A): # your fancy new class
    def __init__(self, field, field2):
        self.field = field
        self.field2 = field2 # B has some fancy extra stuff

def b_from_a(a_instance, field2):
    """Given an instance of A, return a new instance of B."""
    return B(a_instance.field, field2)


a = A("spam") # this Could be your A instance from the library
b = b_from_a(a, "ham") # make a new B which has the data from a

print b.field, b.field2 # prints "spam ham"

编辑:根据您的情况, 可能是一个不错的选择;那是您的B类可能只包含A的实例,而不是继承:

class B2: # doesn't have to inherit from A
    def __init__(self, a, field2):
        self._a = a # using composition instead
        self.field2 = field2

    @property
    def field(self): # pass accesses to a
        return self._a.field
    # Could provide setter, deleter, etc

a = A("spam")
b = B2(a, "ham")

print b.field, b.field2 # prints "spam ham"
python 2022/1/1 18:27:55 有191人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶