简体   繁体   English

你能做一个普通的 python class 冷冻吗?

[英]can you make a regular python class frozen?

It's useful to be able to create frozen dataclasses.能够创建冻结的数据类很有用。 I'm wondering if there is a way to do something similar for regular python classes (ones with an __init__ function with complex logic possibly).我想知道是否有一种方法可以为常规 python 类(可能具有复杂逻辑的__init__ function 类)做类似的事情。 It would be good to prevent modification after construction in some kind of elegant way, like frozen dataclasses.以某种优雅的方式防止构造后的修改会很好,比如冻结数据类。

yes.是的。

All attribute access in Python is highly customizable, and this is just a feature dataclasses make use of. Python 中的所有属性访问都是高度可定制的,这只是一个功能数据类利用。

The easiest way to control attribute setting is to create a custom __setattr__ method in your class - if you want to be able to create attributes during __init__ one of the ways is to have an specific parameter to control whether each instance is frozen already, and freeze it at the end of __init__ :控制属性设置的最简单方法是在您的__setattr__中创建自定义 __setattr__ 方法 - 如果您希望能够在__init__期间创建属性,其中一种方法是使用特定参数来控制每个实例是否已经冻结,并冻结它在__init__的末尾:

class MyFrozen:
   _frozen = False
   def __init__(self, ...):
       ...
       self._frozen = True

   def __setattr__(self, attr, value):
       if getattr(self, "_frozen"):
            raise AttributeError("Trying to set attribute on a frozen instance")
       return super().__setattr__(attr, value) 

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

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