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 TypeError
in any calculation which happens to stumble over the wrong value type. Bonus: standard operations already do this.
>>> 3.0 / 'abc'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for /: 'float' and 'str'
Duck Typing is the usual way in Python. It should work with anything that behaves like a number, but not necessarily is a real number.
In most cases in Python one should not explicitly check for types. You gain flexibility because your code can be used with custom datatypes, as long as they behave correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With