我有以下类(class):
class C3DPoint(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
# Other methods
我想确定如果有人设置
v3dpoint.x = <sth>
如果 vale 不是字符串,它会引发错误。如何才能做到这一点?
最佳答案
良好的 Python 设计避免显式类型检查:“如果它像鸭子一样嘎嘎叫,那就是鸭子......”。因此,您应该首先尝试在类之外执行数据验证,或者根本不执行。
话虽如此,执行检查的一种方法是重新定义 __setattr__
as described here :
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 - 如何在python中强制属性为int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53208005/