阻止为类或modu创建新属性

2024-10-01 17:41:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我在SOPrevent creating new attributes outside init上看到了这个问题,它显示了如何防止向类的对象添加新属性。你知道吗

我希望整个类甚至整个加载的模块都有相同的行为。你知道吗

示例类:

class Klass:
     a = 0
     b = 1

另一个模块:

from Klass import Klass

Klass.c = 2 # this should raise an error

这可能吗?你知道吗


Tags: 模块对象fromimportcreating示例new属性
2条回答

如果您试图阻止修改类本身,那么可以创建一个元类来定义类的__setattr__方法。你知道吗

class FrozenMeta(type):
    def __new__(cls, name, bases, dct):
        inst = super().__new__(cls, name, bases, {"_FrozenMeta__frozen": False, **dct})
        inst.__frozen = True
        return inst
    def __setattr__(self, key, value):
        if self.__frozen and not hasattr(self, key):
            raise TypeError("I am frozen")
        super().__setattr__(key, value)

class A(metaclass=FrozenMeta):
    a = 1
    b = 2

A.a = 2
A.c = 1 # TypeError: I am frozen

槽的答案将是Pythonic的方法。你知道吗

class Klass:
    __slots__ = ['a', 'b']

    def __init__(self, a=0, b=1):
        self.a = a
        self.b = b
>>> k = klass.Klass()
>>> k.a
0
>>> k.b
1
>>> k.c = 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Klass' object has no attribute 'c'
>>>

相关问题 更多 >

    热门问题