class Point():
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __setattr__(self, name, value):
assert isinstance(value, str), "Value must be of type str"
super().__setattr__(name, value)
p = Point('a', 'b', 'c')
p.x = 3
# AssertionError: Value must be of type str
你可以这样做:
您可以在Python中键入函数参数,假设您使用的是当前版本,但目前不确定是哪个PEP实现了它。你知道吗
然而,这不会抛出打字错误,因为我们都是同意的成年人,因为你可以做一个类型检查。你知道吗
好的Python设计避免了显式类型检查:“如果它像鸭子一样呱呱叫,那就是鸭子……”。因此,您应该首先尝试在类之外执行数据验证,或者根本不执行。你知道吗
说到这里,执行检查的一种方法是重新定义
__setattr__
as described here:相关问题 更多 >
编程相关推荐