【问题标题】:python instantiate child instance from parent objectpython从父对象实例化子实例
【发布时间】:2021-06-01 01:46:49
【问题描述】:

我有一个从父类实例化的对象(它将在下面的示例代码中成为变量) 我想在不了解父类成员变量的情况下像子类实例一样使用这个对象

有什么推荐的吗?

class A:
    def __init__(self):
        pass # some member variables are assigned
    pass

class B(A):
    def test(self):
        print("test")
    pass

b = A()
b.test() # error

【问题讨论】:

  • 你的用例是什么?
  • @bdbd 感谢您的回复。实际上我使用 pyvisa 库。我想继承资源类并创建自己的类。资源管理器连接到仪器并返回资源实例。所以我只想像我自己的类一样使用返回的资源对象
  • session = visa.ResourceManager.open_resource(visa_resource_name) 在这种情况下。我想像我自己的类对象一样使用会话

标签: python inheritance


【解决方案1】:

您可以通过将b 的__class__ 设置为B 来实现此目的。但请先阅读: https://stackoverflow.com/a/13280789/6759844

class A:
    def __init__(self):
        pass # some member variables are assigned
    pass

class B(A):
    def test(self):
        print("test")
    pass

b = A()
b.__class__ = B
b.test() # error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    相关资源
    最近更新 更多