Reputation: 133
I have to use a class
. I have to make sure that x
and y
are properties.
If the values provided are not convertible to an integer, raise an AttributeError
. If we give a value less than 0
to x
or y
, it is assigned the value 0
.
If we give a value greater than 10
to x
or y
, it is assigned the value 10
.
Here is my code:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def getx(self):
x=int()
return self._x
def gety(self):
y=int()
return self._y
if x>=0:
return 0
else if x<=10:
return 10
I want to obtain this:
p = Point(1,12)
print(p.x, p.y) # output "1 10"
p.x = 25
p.y = -5
print(p.x, p.y) # output "10 0"
Upvotes: 0
Views: 38
Reputation: 195428
What are you looking for is clamp()
function, which takes 3 arguments: value, desired minimal value and desired maximal value.
Properties are defined by the @property
decorator. For testing if the value assigned to property is number I use numbers
module. Here is sample code:
import numbers
def clamp(v, _min, _max):
return max(min(v, _max), _min)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@property
def x(self):
return self.__x
@x.setter
def x(self, value):
if not isinstance(value, numbers.Number):
raise AttributeError()
self.__x = clamp(int(value), 0, 10)
@property
def y(self):
return self.__y
@y.setter
def y(self, value):
if not isinstance(value, numbers.Number):
raise AttributeError()
self.__y = clamp(int(value), 0, 10)
p = Point(1,12)
print(p.x, p.y) # output "1 10"
p.x = 25
p.y = -5
print(p.x, p.y) # output "10 0"
Upvotes: 2