【问题标题】:Python change object reference from object itselfPython从对象本身更改对象引用
【发布时间】:2014-08-10 20:20:02
【问题描述】:

考虑以下代码:

class A:
    def hi(self):
        print 'A'
    def change(self):
        self = B()
class B(A):
    def hi(self):
        print 'B'

test = A()
test.hi() -> prints A
test.change()
test.hi() -> prints A, should print B

有什么方法可以使这个原理起作用,所以从类/对象本身更改对象引用“测试”?

【问题讨论】:

  • 您正在更改局部变量 self 而不是实例。
  • 我知道这一点,但是我正在寻找一种解决方案来从对象/类中更改实例

标签: python class oop reference


【解决方案1】:

对象没有包含它们的变量的概念 - 因此,您不能完全按照您想要做的事情。

你可以做的是有一个知道它包含的东西的容器:

class Container(object):
    def __init__(self):
        self.thing = A()
    def change(self):
        self.thing = B()
    def hi(self):
        self.thing.hi()

test = Container()
test.hi() # prints A
test.change()
test.hi() # prints B

【讨论】:

    猜你喜欢
    • 2015-03-30
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    相关资源
    最近更新 更多