Assume a class like this, where attribute x has to be either an integer or a float:
class foo(object):
def __init__(self,x):
if not isinstance(x,float) and not isinstance(x,int):
raise TypeError('x has to be a float or integer')
else:
self.x = x
Assigning a non-integer and non-float to x will return an error when instantiating the class:
>>> f = foo(x = 't')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __init__
TypeError: x has to be a float or integer
But the direct assignment of x does not return any errors:
>>> f = foo(x = 3)
>>> f.x = 't'
>>>
How can I make python raise an error in the latter case?