在Python中将对象强制转换为派生类型

在Python中将对象强制转换为派生类型,python,type-conversion,Python,Type Conversion,我想将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类型的对象强制转换为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

通常的方法是为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)

顺便说一句,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

据我所知,这在Python中并不存在。您应该编写一个函数,该函数接受类型a的对象,并返回类型B的对象,例如,通过将类型a对象的属性复制到新的类型B对象。我看到了答案,但我希望得到更具python风格的东西。您对此有任何实际的使用案例吗。代码的getAThing返回类A的对象,您认为如何将其转换为类B。我认为在Java中,它看起来是这样的:B A_thing=(B)Foo.getAThing();另外,如果您使用
classmethod
,您可以(也许应该?)使用
cls
对象初始化返回的对象:
返回cls(value,other_value)
如果类C将从B继承,并且用户调用
C,则从a(…)
它将返回C而不是B。