由于库函数返回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"