Reputation: 77
There is a pythonic way to control attributes? I wan't that the init method is clear, trying to avoid to use a function like:
self.a = check_a_greater_than_b(a)
and avoid to do controls in the init method
def __init__(self, a, b):
if b > a:
raise AttributeError('A should be > B')
else:
self.a = a
self.b = b
I was think to use the setter or settattr, can you post me an example please?
Upvotes: 1
Views: 38
Reputation: 445
You can do something like this :
class Object():
def __init__(self, a, b):
self.b = b
self.a = a
@property
def a(self):
return self.__a
@a.setter
def a(self, a):
assert a > self.b, "A should be > B"
self.__a = a
Then you will have :
o = Object(3,2)
o.a = 1
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 12, in a
AssertionError: A should be > B
Upvotes: 1