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
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
您可以重写类“
__setattr__
”,并执行任何需要的检查。在这个例子中,我不允许和设置未在构造函数中定义的成员。它将使您不必手动维护该列表。你知道吗你可以使用
__slots__
-看看the documentation。你知道吗在未知属性上引发的异常将是
AttributeError
。你知道吗必须确保使用新样式的类才能工作(显式地从
object
继承)相关问题 更多 >
编程相关推荐