Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python change object reference from object itself

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?

like image 389
Stefan Avatar asked Sep 17 '25 06:09

Stefan


1 Answers

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
like image 193
Amber Avatar answered Sep 20 '25 07:09

Amber