繁体   English   中英

python 范围 class 实例属性如何只读?

[英]How are the python range class instance attributes readonly?

python 的内置范围 class 具有以下行为

x = range(1)
x.step = 10
AttributeError: 'range' object attribute 'step' is read-only

现在我知道我们可以通过使用@property 装饰器来获得这种行为。 但是要让属性装饰器工作,它必须引用实例的另一个属性/方法。

在 class 范围的一个实例中,我看不到任何其他方法或 dunder(double under) 或包含 value 步骤的属性。

这是如何实现的。 这是否可能在纯 python 中没有@property 的情况下实现,或者这是在 class 中实现的 class 中的构建范围中的情况,在 C 中实现,而不是在纯 Z23EEEB4934BDD76BDD66BDBDD765BDD6EZ937Z 中实现。

如果您尝试设置step ,则可以覆盖__setattr__以引发错误。

class range:
    __slots__ = ['step']

    def __init__(self, *args):
        pass

    def __setattr__(self, attr, value):
        if attr == "step":
            raise AttributeError("'range' object attribute 'step' is read-only")

__slots__的定义阻止您尝试类似x.__dict__['step'] = 10东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM