如何防止python对象添加变量
class baseClass1:
count=0;
def displayCount(self):
print "Total Employee %d" % baseClass1.count;
base = baseClass1();
base.type = "class"; # i want to throw an error here
答案 0 :(得分:2)
您可以使用__slots__
- 查看the documentation。
class baseClass1(object):
__slots__ = ['count']
未知属性抛出的异常将是AttributeError
。
你必须确保使用新式的类来实现(显式继承自object
)
答案 1 :(得分:1)
您可以覆盖班级“__setattr__
并执行您想要的任何检查。在这个例子中,我不允许和设置未在构造函数中定义的成员。它将使您免于手动维护该列表。
class baseClass1:
# allowed field names
_allowed = set()
def __init__(self):
# init stuff
self.count=0
self.bar = 3
# now we "freeze the object" - no more setattrs allowed
self._frozen = True
def displayCount(self):
print "Total Employee %d" % baseClass1.count;
def __setattr__(self, name, value):
# after the object is "frozen" we only allow setting on allowed field
if getattr(self, '_frozen', False) and name not in self.__class__._allowed:
raise RuntimeError("Value %s not allowed" % name)
else:
# we add the field name to the allowed fields
self.__class__._allowed.add(name)
self.__dict__[name] = value
base = baseClass1();
base.count = 3 #won't raise
base.bar = 2 #won't raise
base.type = "class"; # throws