1. 程式人生 > >006_005 Python 繼承的替代方案,自動託管

006_005 Python 繼承的替代方案,自動託管

程式碼如下:

#encoding=utf-8

print '中國'

#繼承的替代方案,自動託管 功能:比如可以隱藏基類的某些方法


try: set
except NameError: from sets import Set as set

class ROError(AttributeError):pass

class ReadOnly:
    mutators = {
       list: set('''__delitem__ __delslice__ __iadd__ __imul__
                __setitem__ __setslice__ append extend insert
                pop remove sort'''.split( )),
       dict: set('''__delitem__ __setitem__ clear pop popitem
                setdefault update'''.split( )),
       }
    def __init__(self, o):
       object.__setattr__(self, '_o', o)
       object.__setattr__(self, '_no', self.mutators.get(type(o), ( )))
    def __setattr__(self, n, v):
       raise ROError, "Can't set attr %r on RO object" % n
    def __delattr__(self, n):
       raise ROError, "Can't del attr %r from RO object" % n
    def __getattr__(self, n):
       if n in self._no:
           raise ROError, "Can't get attr %r from RO object" % n
       return getattr(self._o, n)


class Person(ReadOnly):
    def __init__(self,name):
        self.name = name
    def set_name(self,name):
        self.name=name

Persona=Person('a')

列印結果如下:

中國
Traceback (most recent call last):
  File "F:\workspace\StudyPy\src\basic\study006_005.py", line 40, in <module>
    Persona=Person('a')
  File "F:\workspace\StudyPy\src\basic\study006_005.py", line 36, in __init__
    self.name = name
  File "F:\workspace\StudyPy\src\basic\study006_005.py", line 25, in __setattr__
    raise ROError, "Can't set attr %r on RO object" % n
__main__.ROError: Can't set attr 'name' on RO object