2

我想将 A 类型的对象转换为 B 类型,这样我就可以使用 B 的方法。B类继承A。例如我有我的类B:

class B(A):
    def hello(self):
        print('Hello, I am an object of type B')

我的库 Foo 有一个函数,它返回一个 A 类型的对象,我想将它转换为 B 类型。

>>>import Foo
>>>a_thing = Foo.getAThing()
>>>type(a_thing)
A
>>># Somehow cast a_thing to type B
>>>a_thing.hello()
Hello, I am an object of type B
4

2 回答 2

1

执行此操作的常用方法是为 B 编写一个类方法,该方法接受一个 A 对象并使用其中的信息创建一个新的 B 对象。

class B(A):
    @classmethod
    def from_A(cls, A_obj):
       value = A.value
       other_value = A.other_value
       return B(value, other_value)

a_thing = B.from_A(a_thing)
于 2013-07-19T00:14:19.073 回答
0

AFAIK,Python 中没有子类化。您可以做的是创建另一个对象并复制所有属性。您的 B 类构造函数应采用 A 类型的参数以复制所有属性:

class B(A):
  def __init__(self, other):
    # Copy attributes only if other is of good type
    if isintance(other, A):
      self.__dict__  = other.__dict__.copy()
  def hello(self):
    print('Hello, I am an object of type B')

然后你可以写:

>>> a = A()
>>> a.hello()
Hello, I am an object of type A
>>> a = B(a)
>>> a.hello()
Hello, I am an object of type B
于 2013-07-19T00:16:40.217 回答