我有一个有几个属性的类。我可以使用@property装饰器来验证每个属性。但是,我也想验证条件属性。现在,我正在使用在init方法中调用的验证函数。有更好的办法吗?
我现在就是这样做的。
class Foo:
def __init__(self, x, y):
self.x = x
self.y = y
self.validate()
def validate(self):
if self.x > 100 and self.y > 100:
raise ValueError("Object outside of bounds!")
elif isintance(self.y, int) and not isintance(self.x, int):
raise ValueError("Mismatched types!")
elif...发布于 2022-05-16 20:25:29
我将在__init__中直接使用助手函数进行验证。
class Foo:
def __init__(self, x, y):
if x > 100 and y > 100:
raise ValueError("x and y cannot both be greather than 100")
if not (isinstance(x, type(y)) and isinstance(y, type(x))):
raise ValueError("x and y have different types")
self.x = x
self.y = y
class Bar:
def __init__(self, x, y):
self.validate(x, y)
self.x = x
self.y = y
@staticmethod
def validate(x, y) -> bool:
if x > 100 and y > 100:
raise ValueError("x and y cannot both be greather than 100")
if not (isinstance(x, type(y)) and isinstance(y, type(x))):
raise ValueError("x and y have different types")
return Truehttps://stackoverflow.com/questions/72265008
复制相似问题