【问题标题】:Cast an object to a derived type in Python在 Python 中将对象强制转换为派生类型
【发布时间】:2013-07-19 00:02:50
【问题描述】:

我想将 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

【问题讨论】:

  • 据我所知,这在 Python 中不存在。您应该编写一个函数,该函数接受 A 类型的对象,并返回 B 类型的对象,例如,将 A 类型对象的属性复制到新的 B 类型对象。
  • 我看到了this question 的答案,但我希望有更多 Pythonic 的东西。
  • 你有这方面的实际用例吗?您的代码的 getAThing 正在返回 A 类的对象,您认为它如何转换为 B 类。
  • 我认为在 Java 中它看起来像这样:B a_thing = (B) Foo.getAThing();

标签: python type-conversion


【解决方案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)

【讨论】:

  • 另外,如果你使用了classmethod,你可以(也许应该?)使用cls对象来初始化返回的对象:return cls(value, other_value)这样,如果类C将从B和用户继承调用 C.from_a(...) 它将返回 C 而不是 B。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2015-03-27
    • 2011-07-15
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 2012-08-29
    • 2015-05-29
    相关资源
    最近更新 更多