python - 如何在python中强制属性为int?

标签 python oop

我有以下类(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/

相关文章:

python - 如何让wxpython在单元测试中捕获线程事件?

java - 除了拥有正确的方法之外,还有更多的接口(interface)吗

java - 这是地道的Java吗?

python - 一次在数据框中进行多项操作

oop - Matlab 代理类问题。 (关于 : dependent properties)

javascript - CoffeeScript:对象初始化器中的 Getter/Setter

python - 无法在python中访问基类中的父类成员

python - 心理生成器 : how to update screen each keypress?

python - TPOT P@K 定制记分器

python - 困惑为什么这段代码不会打印任何内容