I've created a skeleton Point class for points in a 3D space (e.g. with x, y, and z co-ordinates). I want the co-ordinates to be integers and for any other input value to be refused. That part works fine. I just can't figure out a way to have the class constructor refuse to initialize an object if any of the three inital values is not an integer. How do I do that? Here's my code so far:
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
@property
def x(self):
return self.__x
@x.setter
def x(self, a):
if isinstance(a, int):
self.__x = a
else:
print("x must be an integer")
return None
@property
def y(self):
return self.__y
@y.setter
def y(self, b):
if isinstance(b, int):
self.__y = b
else:
print("y must be an integer")
return None
@property
def z(self):
return self.__z
@z.setter
def z(self, c):
if isinstance(c, int):
self.__z = c
else:
print("z must be an integer")
return None
Just raise an exception, like so
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
@property
def x(self):
return self.__x
@x.setter
def x(self, a):
if isinstance(a, int):
self.__x = a
else:
raise AttributeError("x must be an integer")
@property
def y(self):
return self.__y
@y.setter
def y(self, b):
if isinstance(b, int):
self.__y = b
else:
raise AttributeError("y must be an integer")
@property
def z(self):
return self.__z
@z.setter
def z(self, c):
if isinstance(c, int):
self.__z = c
else:
raise AttributeError("z must be an integer")
p = Point(1, 2, 3.5)
I tried this:
b = Point(0.5, 3, -7)
With this result:
TypeError: __init__() missing 1 required positional argument: 'z'
While that attained my goal of not having the Point object instantiated with one or more invalid parameters, the error message is confusing. Is there something I can do about that?
That peculiar. Could you post your class Point again?
I dont that error message, and see the expected behaviour.
b = Point(0.5, 3, -7)
Output:
Traceback (most recent call last):
File "main.py", line 41, in <module>
b = Point(0.5, 3, -7)
File "main.py", line 4, in __init__
self.x = x
File "main.py", line 17, in x
raise AttributeError("x must be an integer")
AttributeError: x must be an integer
exited with non-zero status