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

霜冻

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

我得到了一个实例a我想转换a为一个类B,使其在各个方面都保持相同,除了method2(存在于原始类中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

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

SorousH Bakhtiary

您可以将对象重新分配__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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章