在 Python 中将对象转换为子类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/597199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:25:23  来源:igfitidea点击:

Converting an object into a subclass in Python?

python

提问by saffsd

Lets say I have a library function that I cannot change that produces an object of class A, and I have created a class B that inherits from A.

假设我有一个无法更改的库函数,它生成一个类 A 的对象,并且我创建了一个继承自 A 的类 B。

What is the most straightforward way of using the library function to produce an object of class B?

使用库函数生成 B 类对象的最直接方法是什么?

edit- I was asked in a comment for more detail, so here goes:

编辑 - 我在评论中被问到更多细节,所以这里是:

PyTables is a package that handles hierarchical datasets in python. The bit I use most is its ability to manage data that is partially on disk. It provides an 'Array' type which only comes with extended slicing, but I need to select arbitrary rows. Numpy offers this capability - you can select by providing a boolean array of the same length as the array you are selecting from. Therefore, I wanted to subclass Array to add this new functionality.

PyTables 是一个在 python 中处理分层数据集的包。我最常用的一点是它能够管理部分在磁盘上的数据。它提供了一个仅带有扩展切片的“数组”类型,但我需要选择任意行。Numpy 提供此功能 - 您可以通过提供与您从中选择的数组长度相同的布尔数组来进行选择。因此,我想继承 Array 以添加这个新功能。

In a more abstract sense this is a problem I have considered before. The usual solution is as has already been suggested- Have a constructor for B that takes an A and additional arguments, and then pulls out the relevant bits of A to insert into B. As it seemed like a fairly basic problem, I asked to question to see if there were any standard solutions I wasn't aware of.

在更抽象的意义上,这是我之前考虑过的一个问题。通常的解决方案是已经建议的 - 有一个 B 的构造函数,它接受一个 A 和额外的参数,然后拉出 A 的相关位插入到 B 中。因为这似乎是一个相当基本的问题,我问看看是否有任何我不知道的标准解决方案。

采纳答案by Kiv

Since the library function returns an A, you can't make it return a B without changing it.

由于库函数返回 A,因此您不能在不更改它的情况下使其返回 B。

One thing you can do is write a function to take the fields of the A instance and copy them over into a new B instance:

您可以做的一件事是编写一个函数来获取 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"

Edit: depending on your situation, composition instead of inheritancecould be a good bet; that is your B class could just contain an instance of A instead of inheriting:

编辑:根据您的情况,组合而不是继承可能是一个不错的选择;那就是你的 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"

回答by ironfroggy

This can be done if the initializer of the subclass can handle it, or you write an explicit upgrader. Here is an example:

如果子类的初始化程序可以处理它,或者您编写显式升级程序,则可以完成此操作。下面是一个例子:

class A(object):
    def __init__(self):
        self.x = 1

class B(A):
    def __init__(self):
        super(B, self).__init__()
        self._init_B()
    def _init_B(self):
        self.x += 1

a = A()
b = a
b.__class__ = B
b._init_B()

assert b.x == 2

回答by J?rn Hees

you can actually change the .__class__attribute of the object if you know what you're doing:

如果您知道自己在做什么,您实际上可以更改.__class__对象的属性:

In [1]: class A(object):
   ...:     def foo(self):
   ...:         return "foo"
   ...:

In [2]: class B(object):
   ...:     def foo(self):
   ...:         return "bar"
   ...:

In [3]: a = A()

In [4]: a.foo()
Out[4]: 'foo'

In [5]: a.__class__
Out[5]: __main__.A

In [6]: a.__class__ = B

In [7]: a.foo()
Out[7]: 'bar'

回答by Andrew Dalke

Monkeypatch the library?

猴子补丁图书馆?

For example,

例如,

import other_library
other_library.function_or_class_to_replace = new_function

Poof, it returns whatever you want it to return.

噗,它返回任何你想要它返回的东西。

Monkeypatch A.newto return an instance of B?

Monkeypatch A. new返回 B 的一个实例?

After you call obj = A(), change the result so obj.class= B?

调用 obj = A() 后,将结果更改为 obj. 班级=B?