alexpad alexpad -4 years ago 83
Python Question

Change object using a dictionary as a link

This code:

class test():
def __init__(self):
self.dog = 'woof'
self.cats = ['meow']
print(self.dog, self.cats)
self.change()
print(self.dog, self.cats)

def change(self):
link = {'dog' : self.dog,
'cats': self.cats}
link['dog'] = 'bark'
link['cats'].append('meow')

a = test()


gives me this output:

woof ['meow']
woof ['meow', 'meow']


When i expected:

woof ['meow']
bark ['meow', 'meow']


I see that
link['dog'] = 'bark'
just changes the dictionary, not the
self.dog
itself. How do i change where
self.dog
points using dictionary?

Edit:
I don't know wether it's possible or not to do what i want using dictionary, but
setattr()
and
getattr()
would work just fine.

def change(self):
setattr(self, 'dog', 'bark')
cats = getattr(self, 'cats')
cats.append('meow')
setattr(self, 'cats', cats)

Answer Source

You can do what you want just by using the built-in link-like dictionary all class instances have: self.__dict__. Here's what I mean:

class Test():
    def __init__(self):
        self.dog = 'woof'
        self.cats = ['meow']
        print(self.dog, self.cats)
        self.change()
        print(self.dog, self.cats)

    def change(self):
        self.__dict__['dog'] = 'bark'
        self.__dict__['cats'].append('meow')

a = Test()

Output:

woof ['meow']
bark ['meow', 'meow']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download