代码之家  ›  专栏  ›  技术社区  ›  Arnav Borborah

如何使类的所有实例变量都是只读的?

  •  0
  • Arnav Borborah  · 技术社区  · 7 年前

    假设我有一门课,如下所示:

    class Test:
        def __init__(self, some_data_source):
            self.a = 5
            self.b = some_data_source['c']
    

    data_source = {
        'c': 'some data'
    }
    
    x = Test(data_source)
    
    # Should be illegal i.e result in an exception
    x.a = 5
    x.b = None
    
    # This should be legal
    print(x.a)
    

    起初,我想 using properties ,但后来我意识到,为了动态地添加它们,我需要在定义类之后添加这些属性(例如 Test.attribute = property(...) __init__

    否则如何使类的所有实例变量都是只读的?

    1 回复  |  直到 7 年前
        1
  •  1
  •   jjmerelo    6 年前

    核对 hasattr __setattr__

    class Test:
        def __init__(self, some_data_source):
            self.a = 5
            self.b = some_data_source['c']
    
        def __setattr__(self, name, value):
            if hasattr(self, name):
                raise ValueError('cannot set %s to %s' %(value, name))
            self.__dict__[name]=value
    
    
    data_source = {
        'c': 'some data'
    }
    
    x = Test(data_source)
    x.b='raise' # this will raise error