Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use `__setattr__`, a property or...?

Tags:

python

I have an object with two attributes, file_path and save_path. Unless save_path is explicitly set, I want it to have the same value as file_path.

I think the way to do this is with __setattr__, with something like the following:

class Class():
...
    def __setattr__(self, name, value):
        if name == 'file_path':
            self.file_path = value
            self.save_path = value if self.save_path == None else self.save_path
        elif name == 'save_path':
            self.save_path = value

But this looks like it's going to give me infinite loops since __setattr__ is called whenever an attribute is set. So, what's the proper way to write the above and avoid that?

like image 344
Chuck Avatar asked Dec 10 '22 15:12

Chuck


1 Answers

First, the easiest way to do this would be with a property:

class Class(object):
    def __init__(self, ...):
        self._save_path = None
        ...
    @property
    def save_path(self):
        if self._save_path is None:
            return self.file_path
        else:
            return self._save_path
    @save_path.setter
    def save_path(self, val):
        self._save_path = val

Second, if you ever find yourself needing to write a __setattr__, you should use super(Class, self).__setattr__ inside your __setattr__ to bypass your __setattr__ and set attributes the normal way, avoiding infinite recursion.

like image 96
user2357112 supports Monica Avatar answered Dec 28 '22 23:12

user2357112 supports Monica