Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change class instance inside an instance method

Any idea if there is a way to make the following code to work

class Test(object):

    def __init__(self, var):
        self.var = var

    def changeme(self):
        self = Test(3)

t = Test(1)
assert t.var == 1
t.changeme()
assert t.var == 3

is something like the following safe to use for more complex objects (like django models, to hot swap the db entry the instance is referring to)

class Test(object):

    def __init__(self, var):
        self.var = var

    def changeme(self):
        new_instance = Test(3)
        self.__dict__ = new_instance.__dict__

t = Test(1)
assert t.var == 1
t.changeme()
assert t.var == 3
like image 671
vinilios Avatar asked Jan 26 '10 06:01

vinilios


1 Answers

self = Test(3) is re-binding the local name self, with no externally observable effects.

Assigning self.__dict__ (unless you're talking about instances with __slots__ or from classes with non-trivial metaclasses) is usually OK, and so is self.__init__(3) to re-initialize the instance. However I'd prefer to have a specific method self.restart(3) which knows it's being called on an already-initialized instance and does whatever's needed to cater for that specific and unusual case.

like image 64
Alex Martelli Avatar answered Nov 10 '22 20:11

Alex Martelli