防止在 __init__ 之外创建新属性
我希望能够创建一个类(在 Python 中),一旦用 __init__ 初始化,不接受新属性,但接受现有属性的修改。我可以看到几种 hack-ish 方法可以做到这一点,例如使用 __setattr__ 方法
def __setattr__(self, attribute, value):
if not attribute in self.__dict__:
print "Cannot set %s" % attribute
else:
self.__dict__[attribute] = value
,然后直接在 __init__ 内部编辑 __dict__ ,但我想知道是否有“正确”的方法来做到这一点?
I want to be able to create a class (in Python) that once initialized with __init__
, does not accept new attributes, but accepts modifications of existing attributes. There's several hack-ish ways I can see to do this, for example having a __setattr__
method such as
def __setattr__(self, attribute, value):
if not attribute in self.__dict__:
print "Cannot set %s" % attribute
else:
self.__dict__[attribute] = value
and then editing __dict__
directly inside __init__
, but I was wondering if there is a 'proper' way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
我不会直接使用 __dict__ ,但您可以添加一个函数来显式“冻结”实例:
I wouldn't use
__dict__
directly, but you can add a function to explicitly "freeze" a instance:插槽是可行的方法:
Pythonic 方法是使用插槽而不是使用
__setattr__
。虽然它可以解决问题,但不会带来任何性能改进。对象的属性存储在字典“__dict__
”中;这就是为什么您可以动态地将属性添加到我们迄今为止创建的类的对象中的原因。使用字典来存储属性非常方便,但对于只有少量实例变量的对象来说可能意味着空间的浪费。当我们设计类时,我们可以使用插槽来阻止动态创建属性。要定义槽,您必须定义一个名为 __slots__ 的列表。该列表必须包含您想要使用的所有属性。我们在下面的类中演示了这一点,其中槽列表仅包含属性“val”的名称。
=>它无法创建属性“new”:
Slots is the way to go:
The pythonic way is to use slots instead of playing around with the
__setattr__
. While it may solve the problem, it does not give any performance improvement. The attributes of objects are stored in a dictionary "__dict__
"; this is the reason why you can dynamically add attributes to objects of classes that we have created so far. Using a dictionary for attribute storage is very convenient, but it can mean a waste of space for objects, which have only a small amount of instance variables.When we design a class, we can use slots to prevent the dynamic creation of attributes. To define slots, you have to define a list with the name
__slots__
. The list has to contain all the attributes, you want to use. We demonstrate this in the following class, in which the slots list contains only the name for an attribute "val".=> It fails to create an attribute "new":
如果有人有兴趣使用装饰器来做到这一点,这里有一个可行的解决方案:
使用起来非常简单:
结果:
If someone is interested in doing that with a decorator, here is a working solution:
Pretty straightforward to use:
Result:
实际上,您不需要
__setattr__
,您需要__slots__
。将 __slots__ = ('foo', 'bar', 'baz') 添加到类主体中,Python 将确保任何实例上都只有 foo、bar 和 baz。但请阅读文档列出的警告!Actually, you don't want
__setattr__
, you want__slots__
. Add__slots__ = ('foo', 'bar', 'baz')
to the class body, and Python will make sure that there's only foo, bar and baz on any instance. But read the caveats the documentation lists!我非常喜欢使用装饰器的解决方案,因为它很容易在项目中的许多类中使用它,并且每个类的添加量最少。但它不适用于继承。
所以这是我的版本:它只覆盖 __setattr__ 函数 - 如果该属性不存在并且调用者函数不是 __init__,它会打印一条错误消息。
I like very much the solution that uses a decorator, because it's easy to use it for many classes across a project, with minimum additions for each class. But it doesn't work well with inheritance.
So here is my version: It only overrides the __setattr__ function - if the attribute doesn't exist and the caller function is not __init__, it prints an error message.
正确的方法是重写
__setattr__
。这就是它的用途。The proper way is to override
__setattr__
. That's what it's there for.@dataclass(slots=True)
Nirvana (Python 3.10)我爱上了这个
@dataclass
thing:main.py
结果:
注意
@dataclass
仅需要我们定义我们的使用键入注释一次属性,然后不重复 我们免费获得:
__slots__ = ['n', 's']
本例中未显示的其他免费内容:
__str__
__eq__
: 通过属性比较对象实例是否相等__hash__ 如果您还使用
frozen=True
: 自定义类型的对象作为字典键在Python 3.10.7、Ubuntu 22.10上测试。
@dataclass(slots=True)
Nirvana (Python 3.10)I'm in love with this
@dataclass
thing:main.py
Outcome:
Note how
@dataclass
only requires us to define our attributes once with type annotationsand then, without any repetition we get for free:
__slots__ = ['n', 's']
Other free things not shown in this example:
__str__
__eq__
: Compare object instances for equality by their attributes__hash__
if you also usefrozen=True
: Object of custom type as dictionary keyTested on Python 3.10.7, Ubuntu 22.10.
这是我想出的方法,不需要 _frozen 属性或方法来在 init 中 freeze() 。
在 init 期间,我只是将所有类属性添加到实例中。
我喜欢这个,因为没有 _frozen、freeze(),并且 _frozen 也不会出现在 vars(instance) 输出中。
Here is approach i came up with that doesn't need a _frozen attribute or method to freeze() in init.
During init i just add all class attributes to the instance.
I like this because there is no _frozen, freeze(), and _frozen also does not show up in the vars(instance) output.
这个怎么样:
What about this:
我喜欢乔亨·里策尔的《冰雪奇缘》。不方便的是打印 Class.__dict 时会出现 isfrozen 变量
我通过创建授权属性列表(类似于插槽)来解决这个问题:
I like the "Frozen" of Jochen Ritzel. The inconvenient is that the isfrozen variable then appears when printing a Class.__dict
I went around this problem this way by creating a list of authorized attributes (similar to slots):
Jochen Ritzel 的
FrozenClass
很酷,但是每次初始化类时调用_frozen()
就不那么酷了(并且您需要冒忘记它的风险)。我添加了一个 __init_slots__ 函数:The
FrozenClass
by Jochen Ritzel is cool, but calling_frozen()
when initialing a class every time is not so cool (and you need to take the risk of forgetting it). I added a__init_slots__
function:没有一个答案提到覆盖
__setattr__
对性能的影响,这在创建许多小对象时可能是一个问题。 (并且__slots__
将是高性能解决方案,但限制pickle/继承)。所以我想出了这个变体,它在初始化后安装我们较慢的settatr:
如果你不想在
__init__
末尾调用freeze
,如果继承是一个问题,或者如果您不希望它出现在vars()
中,那么它也可以进行调整:例如,这里是基于 pystrict 答案的装饰器版本:None of the answers mention the performance impact of overriding
__setattr__
, which can be an issue when creating many small objects. (And__slots__
would be the performant solution but limits pickle/inheritance).So I came up with this variant which installs our slower settatr after init:
If you don't want to call
freeze
at the end of__init__
, if inheritance is an issue, or if you don't want it invars()
, it can also be adapted: for example here is a decorator version based on thepystrict
answer:我写了 pystrict 作为这个问题的解决方案。它太大了,无法将所有代码粘贴到 stackoverflow 中。
pystrict 是一个 pypi 可安装的装饰器,可以与类一起使用来冻结它们。这里的许多解决方案都不能正确支持继承。
如果 __slots__ 不适合您(由于继承问题),这是一个不错的选择。
自述文件中有一个示例,说明了为什么即使您的项目上运行了 mypy 和 pylint,也需要这样的装饰器:
pip install pystrict
然后只需使用 @strict 装饰器:
I wrote pystrict as a solution to this problem. It's too large to paste all of the code in stackoverflow.
pystrict
is a pypi installable decorator that can be used with classes to freeze them. Many solutions here don't properly support inheritance.If
__slots__
doesn't work for you (because of inheritance issues), this is a good alternative.There is an example to the README that shows why a decorator like this is needed even if you have mypy and pylint running on your project:
pip install pystrict
Then just use the @strict decorator: