Python从对象本身更改对象引用

Ste*_*fan 1 python oop reference class

考虑以下代码:

class A:
    def hi(self):
        print 'A'
    def change(self):
        self = B()
class B(A):
    def hi(self):
        print 'B'
Run Code Online (Sandbox Code Playgroud)

test = A()
test.hi() -> prints A
test.change()
test.hi() -> prints A, should print B
Run Code Online (Sandbox Code Playgroud)

是否有某种方法可以使该原理起作用,所以可以将对象引用“测试”从类/对象本身更改为?

Amb*_*ber 5

对象没有包含它们的变量的概念-因此,您无法完全按照自己的意愿去做。

您可以做的是拥有一个知道其所包含内容的容器:

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
Run Code Online (Sandbox Code Playgroud)