2013-07-19 52 views
1

我想将类型A的对象转换为类型B,因此我可以使用B的方法。 B型继承了A.例如,我有我的类B类:在Python中将对象转换为派生类型

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

我的图书馆,富,有一个返回类型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 
功能
+0

据我所知,这并不在Python存在。您应该编写一个接受A类型对象的函数,并通过例如将类型A对象的属性复制到新的B类型对象来返回类型B的对象。 – ChrisP

+0

我看到[这个问题]的答案(http://stackoverflow.com/questions/5663630/object-type-casting-in-python-design-suggestion),但我希望有更多的Pythonic。 – travis1097

+0

你有这方面的任何实际用例。 getAhing代码返回类A的对象,你认为它可以转换为类B. – Karthikeyan

回答

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 
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) 
+0

此外,如果您使用'classmethod',您可以(也许应该?)使用'cls'对象来初始化返回的对象:'返回cls(value,other_value)'如果C类将继承B和用户调用'C.from_a(...)'将返回C而不是B. –

相关问题