Emulating Privacy for Instance Attributes : private « Class « Python Tutorial






class PrivateExc(Exception): pass                 

class Privacy:
    def __setattr__(self, attrname, value):      
        if attrname in self.privates:
            raise PrivateExc(attrname, self)
        else:
            self.__dict__[attrname] = value      

class Test1(Privacy):
    privates = ['age']

class Test2(Privacy):
    privates = ['name', 'pay']
    def __init__(self):
        self.__dict__['name'] = 'Tom'

x = Test1(  )
y = Test2(  )

x.name = 'Bob'
y.name = 'Sue'   # <== fails

y.age  = 30
x.age  = 40      # <== fails








11.24.private
11.24.1.Class with private data members.
11.24.2.Demonstrates private variables and methods
11.24.3.Private Variables
11.24.4.Emulating Privacy for Instance Attributes