Python : 将超类实例转换为子类

Python : Convert Superclass instance to Subclass

我得到了 class A 的对象 a。我不明白 class A 是如何工作的。此外,在我使用的整个模块中,未知数量的方法使用 A。因此,出于所有实际目的,A 是未知的,我们只能操纵它的一个实例和一个已知方法,method2.

我得到了一个实例a。我想将 a 转换为 class B,这样它在每个方面都保持相同,除了 method2(它存在于原始 class A 并打印 a) 现在打印 b。我该如何修改下面的代码才能做到这一点?

class B(A):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)

    def method2(self):
        print('b')

a.method1() #prints '1'
a.method2() #prints 'a'
print(a[0]) #prints 1
#a = convertAtoB(a)
a.method1() #prints '1'
a.method2() #should print 'b'
print(a[0]) #prints 1

我知道以前对涉及使用 __getattr__ 的类似问题的回答,但是在尝试以下代码时:

class B(object):
    def __init__(self, a):
        self.__a = a

    def __getattr__(self, attr):
        return getattr(self.__a, attr)

    def __setattr__(self, attr, val):
        object.__setattr__(self, attr, val)
    
    def method2(self):
        print('b')

在我遇到的实际问题中,我得到了错误 TypeError: 'B' object is not subscriptable

edit : 添加了一个下标测试,正如我上面提到的,我不完全理解 A 是如何工作的或者导入模块中的哪些方法需要 A 才能工作。

不覆盖 __init__,仅覆盖 method2,并仅设置 a = B()。或者:

class B(A):

    def method2(self):
        print('b')

def convertAtoB(a):
    a.method2 = B().method2
    return a

a.method1() #prints '1'
a.method2() #prints 'a'
#a = convertAtoB(a)
a.method1() #prints '1'
a.method2() #should print 'b'

您可以将对象的 __class__ 重新分配给新类型。我在代码中添加了注释:(如有必要,请自行处理对象初始化)

class A:
    def func_A_1(self):
        return 'func_A_1 is running'

    def func_A_2(self):
        return 'func_A_2 is running'

    def method2(self):
        return 'method2 of class A'


class B(A):
    def method2(self):
        return 'method2 of class B'


obj = A()

print(obj)
print(obj.func_A_1())
print(obj.method2())
print('------------------------------')

# turning object of A to B
obj.__class__ = B
print(obj)

# still have access to A's methods
print(obj.func_A_1())

# This method is now for B
print(obj.method2())

输出:

<__main__.A object at 0x0000012FECFACFD0>
func_A_1 is running
method2 of class A
------------------------------
<__main__.B object at 0x0000012FECFACFD0>
func_A_1 is running
method2 of class B