问题描述
我正在做一些分布式计算,其中几台机器在所有机器都具有相同版本的各种类的前提下进行通信.因此,使这些类不可变似乎是一个很好的设计.并非一定要以不良意图阻止用户,只是要使其具有足够的不变性,以至于绝不会偶然修改它.
I'm doing some distributed computing in which several machines communicate under the assumption that they all have identical versions of various classes. Thus, it seems to be good design to make these classes immutable; not in the sense that it must thwart a user with bad intentions, just immutable enough that it is never modified by accident.
我将如何处理?例如,如何实现一个使定义后使用它的类不可变的元类?
How would I go about this? For example, how would I implement a metaclass that makes the class using it immutable after it's definition?
>>> class A(object):
... __metaclass__ = ImmutableMetaclass
>>> A.something = SomethingElse # Don't want this
>>> a = A()
>>> a.something = Whatever # obviously, this is still perfectly fine.
替代方法也可以,例如装饰器/函数,它接受一个类并返回一个不可变的类.
Alternate methods is also fine, such as a decorator/function that takes a class and returns an immutable class.
推荐答案
如果使用 __slots__
不适合您,它或它的某些变体可以做到:只需将您的元类的 __setattr__
方法编写为您的警卫.在此示例中,我阻止分配新属性,但允许修改现有属性:
If the old trick of using __slots__
does not fit you, this, or some variant of thereof can do:simply write the __setattr__
method of your metaclass to be your guard. In this example, I prevent new attributes of being assigned, but allow modification of existing ones:
def immutable_meta(name, bases, dct):
class Meta(type):
def __init__(cls, name, bases, dct):
type.__setattr__(cls,"attr",set(dct.keys()))
type.__init__(cls, name, bases, dct)
def __setattr__(cls, attr, value):
if attr not in cls.attr:
raise AttributeError ("Cannot assign attributes to this class")
return type.__setattr__(cls, attr, value)
return Meta(name, bases, dct)
class A:
__metaclass__ = immutable_meta
b = "test"
a = A()
a.c = 10 # this works
A.c = 20 # raises valueError
这篇关于使类在Python中不可变的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!