python - Should I use `__setattr__`, a property or...? -
i have object 2 attributes, file_path , save_path. unless save_path explicitly set, want have same value file_path.
i think way __setattr__, 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 looks it's going give me infinite loops since __setattr__ called whenever attribute set. so, what's proper way write above , avoid that?
this looks kind of unpythonic. can use attributes. 3 lines of code:
>>> class class: ... def __init__(self, file_path, save_path=none): ... self.file_path=file_path ... self.save_path = save_path or file_path ... >>> c = class('file') >>> c.file_path 'file' >>> c.save_path 'file' >>> c1 = class('file', 'save') >>> c1.file_path 'file' >>> c1.save_path 'save' >>>
Comments
Post a Comment