How to prevent python object from adding variables
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
You can use __slots__ - have a look at the documentation.
class baseClass1(object):
__slots__ = ['count']
The exception thrown on unknown attribute will be AttributeError.
You have to make sure you use the new-style classes for this to work (explicitly inherit from object)
You can override the class' __setattr__ and do whatever checks you want. In this example I'm not allowing and setting of members that were not defined in the constructor. It will save you from manually maintaining that list.
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
if ((((((((expression)))))))):