简体   繁体   中英

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). 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.

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__ :

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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