这里有两个选项:
首先,您可以使用__slots__,它将您的类限制为一组特定的属性。
不完全是您想要的(插槽一开始就不是为此设计的!),但很接近:
class A(object):
__slots__ = ["a"]
a = A()
a.a = 1 # Will work
a.b = 2 # Will not work
其次,您可以覆盖__setattr__,并让它查找一个标志以防止在初始化完成后创建新属性:
class A(object):
__frozen__ = False
def __init__(self, a):
self.a = a
self.__frozen__ = True # At this point no more changes can be made
def __setattr__(self, attr, value):
if self.__frozen__ and not hasattr(self, attr):
raise Exception("New attributes cannot be added!") # Create your own Exception subclass for this
super(A, self).__setattr__(attr, value)
a = A(1)
a.a = 2 # Works
a.b = 2 # Throws an Exception
这更接近你想要的。但是,您应该认真考虑这是否真的可取。这是避免错误的最好方法吗?也许你想例如改为编写测试?
除其他外,如果您的子类调用 super(TheSubClass, self).__init__(*args, **kwargs) 然后尝试访问属性,这将破坏子类化。