I’ve defined a Vector class which has three property variables: x, y and z. Coordinates have to be real numbers, but there’s nothing to stop one from doing the following:
>>> v = Vector(8, 7.3, -1)
>>> v.x = "foo"
>>> v.x
"foo"
I could implement “type safety” like this:
import numbers
class Vector:
def __init__(self, x, y, z):
self.setposition(x, y, z)
def setposition(self, x, y, z):
for i in (x, y, z):
if not isinstance(i, numbers.Real):
raise TypeError("Real coordinates only")
self.__x = x
self.__y = y
self.__z = z
@property
def x(self):
return self.__x
@property
def y(self):
return self.__y
@property
def z(self):
return self.__z
…but that seems un-Pythonic.
Suggestions?
You have to ask yourself why you want to test type on setting these values. Just raise a
TypeErrorin any calculation which happens to stumble over the wrongvaluetype. Bonus: standard operations already do this.