阻止python对象添加variab

2024-04-26 00:26:37 发布

您现在位置:Python中文网/ 问答频道 /正文

如何防止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

Tags: to对象selfbasedeftypecountemployee
2条回答

您可以重写类“__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

你可以使用__slots__-看看the documentation。你知道吗

class baseClass1(object):
    __slots__ = ['count']

在未知属性上引发的异常将是AttributeError。你知道吗

必须确保使用新样式的类才能工作(显式地从object继承)

相关问题 更多 >