我有以下课程:
class C3DPoint(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
# Other methods
Run Code Online (Sandbox Code Playgroud)
我想确保如果有人设置v3dpoint.x = <sth>它会在 vale 不是字符串的情况下抛出错误。
如何才能做到这一点?
好的 Python 设计会避免显式的类型检查:“如果它像鸭子一样嘎嘎叫,那么它就是鸭子......”。因此,您应该首先尝试在类之外执行数据验证,或者根本不执行。
话虽如此,执行检查的一种方法是重新定义,__setattr__ 如下所述:
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
Run Code Online (Sandbox Code Playgroud)