请考虑以下代码:
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
有没有办法让这个原则起作用,所以用类/对象本身改变对象引用'test'?
答案 0 :(得分:4)
对象没有包含它们的变量的概念 - 因此,你无法完全按照自己的意图去做。
你可以做的是让一个容器知道它包含的内容:
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