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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With