Reputation: 11949
Consider the two following class definitions in which, in order to do additional checks before assigning a value to an attribute (e.g., keep track of modified variables, check for validity, etc.) in the first one I override the __setattr__
method and in the second one I use properties.
class A(object):
def __init__(self, x):
self.x = x
def __setattr__(self, name, value):
# do something
self.__dict__[name] = value
class B(object):
def __init__(self, x):
self.x = x
@property
def x(self):
return self.x
@x.setter
def x(self, v):
# do something
self.x = v
To me, it looks like they behave at the same way.
Is there any difference between the two? Which one should be preferred and why?
Upvotes: 2
Views: 87
Reputation: 532238
__setattr__
is more general, as it will run for A().foo = 3
, no matter what attribute foo
you provide. Property setters are specific to a single, explicitly defined property, and can't be used to "accidentally" create an attribute.
Upvotes: 2