我有以下代码:
class Position:
def __int__(self, x: int, y: int):
if out_of_range(x, 0, MAX_INT - 1):
raise ValueError("[error][{}.{}()] Failed to create position: {}n".format(__class__,
inspect.stack()[0].function,
"x must be in range [0, MAX_INT)"
))
if out_of_range(y, 0, MAX_INT - 1):
raise ValueError("[error][{}.{}()] Failed to create position: {}n".format(__class__,
inspect.stack()[0].function,
"y must be in range [0, MAX_INT)"
))
self.__x: int = x
self.__y: int = y
我想创建一个Position的静态实例,x和y都等于MAX_INT。
我该如何编写代码才能做到这一点:
if Position(2, 3) == Position.INVALID: # INVALID <=> Position(MAX_INT, MAX_INT)
...
编辑:
我在Position类中有另一个方法:
def to(self, direction: Direction, steps: int = 1) -> 'Position':
"""
Creates a new position, to the given direction.
If one of the new coordinates goes below 0, then Position.INVALID is returned.
A negative 'steps' value inverses the direction. Ex: Position.to(RIGHT, 3) == Position.to(LEFT, -3)
"""
delta_x, delta_y = DIRECTION_DELTA[direction]
try:
return Position(self.__x + delta_x * steps, self.__y + delta_y * steps)
except ValueError:
return Position.INVALID
更具体地说,我的预期用法是
if Position(2, 3).to(LEFT, 3) == Position.INVALID:
do something
else:
do something else
第一种方法是添加另一个方法来检查一个位置是否有效。
def to(self, direction: Direction, steps: int = 1) -> 'Position':
"""
Creates a new position, to the given direction.
If one of the new coordinates goes below 0, then Position.INVALID is returned.
A negative 'steps' value inverses the direction. Ex: Position.to(RIGHT, 3) == Position.to(LEFT, -3)
"""
delta_x, delta_y = DIRECTION_DELTA[direction]
try:
return Position(self.__x + delta_x * steps, self.__y + delta_y * steps)
except ValueError:
position: Position = Position(0, 0)
position.__x = MAX_INT
position.__y = MAX_INT
return position
def is_valid() -> bool:
return not self.__x == self.__y == MAX_INT
但是现在,Position(MAX_INT, MAX_INT)不再是单例。
第二种方法是让方法to()
从构造函数抛出错误,并在Position.to()
之外捕获它。
不确定这是否是您需要的,但使用装饰器@classmethod
和定义__eq__
,您可以创建一个实例与x=MAX_INT
并将其与您的实例进行比较:
class Position:
def __init__(self, x: int):
if x > MAX_INT:
raise ValueError
self.__x: int = x
def __eq__(self, other):
if self.__x == other.__x:
return True
return False
@classmethod
def INVALID(cls):
p = Position(0)
p.__x = MAX_INT
return p
def to(self, direction: Direction, steps: int = 1) -> 'Position':
delta_x, delta_y = DIRECTION_DELTA[direction]
try:
return Position(self.__x + delta_x * steps, self.__y + delta_y * steps)
except ValueError:
return Position.INVALID()
if Position(MAX_INT-1) == Position.INVALID():
print('invalid')
else:
print('valid')