Consider the following code:
class A:
def hi(self):
print 'A'
def change(self):
self = B()
class B(A):
def hi(self):
print 'B'
and
test = A()
test.hi() -> prints A
test.change()
test.hi() -> prints A, should print B
Is there some way to make this principle work, so changing the object reference 'test' from withing the class/object itself?
Objects have no concept of the variable that contains them - thus, you can't do exactly what you're trying to do.
What you could do is have a container that is aware of the thing it contains:
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments