我一直在使用以下方法来“冻结”Python中的类实例,这样如果我无意中定义了一个新的实例变量,就会出现错误,而不仅仅是让我这样做。
class FrozenClass(object):
__isfrozen = False
def __setattr__(self, key, value):
if self.__isfrozen and key not in dir(self):
raise TypeError( "%r is a frozen class" % self )
object.__setattr__(self, key, value)
def _freeze(self):
self.__isfrozen = True
## so that if you're inheriting a frozen class you can unfreeze it
def _unfreeze(self):
self.__isfrozen = False
其中有效:
>>> class Foo(FrozenClass):
... def __init__(self):
... self.a = 1
... self._freeze()
...
>>> myInstance = Foo()
>>> myInstance.A = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/XXX/Desktop/Git/functions/FrozenClass.py", line 6, in __setattr__
raise TypeError( "%r is a frozen class" % self )
TypeError: <__main__.Foo object at 0x10075c4e0> is a frozen class
>>>
然而,我一直在使用一个全局数据对象,我已经使其成为静态的,但它不起作用。我试过玩它但无济于事。这就是现在的情况:
## doesn't currently work. Not sure.
class FrozenStaticClass(object):
__isfrozen = False
def __setattr__(cls, key, value):
if cls.__isfrozen and key not in dir(cls):
raise TypeError( "%r is a frozen class" % cls )
object.__setattr__(cls, key, value)
@classmethod
def _freeze(cls):
cls.__isfrozen = True
@classmethod
def _unfreeze(cls):
cls.__isfrozen = False
如何让它冻结静态类?
编辑: @volcano建议使用插槽但它似乎不适用于类变量。