擅长:python、mysql、java
<p>如果使用<a href="https://docs.python.org/3/reference/datamodel.html#slots" rel="nofollow">^{<cd1>}</a>的旧技巧不适合您,则此技巧或其某些变体可以:
只需编写元类的<a href="https://docs.python.org/3/reference/datamodel.html#object.__setattr__" rel="nofollow">^{<cd2>}</a>方法来保护您。在本例中,我防止分配新属性,但允许修改现有属性:</p>
<pre><code>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
</code></pre>