版权声明:本文为博主原创文章,未经博主允许不得转载。不经过允许copy,讲追究法律责任,欢迎加入我们的学习QQ群967254284,可以相互交流 https://blog.csdn.net/houyj1986/article/details/23315623
代码如下:
#encoding=utf-8
print '中国'
#禁止添加新的属性
def no_new_attributes(wrapped_setattr):
def __setattr__(self, name, value):
if hasattr(self, name): # not a new attribute, allow setting
wrapped_setattr(self, name, value)
else: # a new attribute, forbid adding it
raise AttributeError("can't add attribute %r to %s" % (name, self))
return __setattr__
#核心在于设置不能添加新的属性,即修改自带的__setattr__函数
class NoNewAttrs(object):
__setattr__ = no_new_attributes(object.__setattr__)
class __metaclass__(type):
__setattr__ = no_new_attributes(type.__setattr__)
class Person(NoNewAttrs):
firstname = ''
lastname = ''
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def __repr__(self):
return 'Person(%r, %r)' % (self.firstname, self.lastname)
me = Person("Michere", "Simionato")
print me
me.firstname = "Michele"
print me
#Exception 不能修改属性
try: Person.address = ''
except AttributeError, err: print 'raised %r as expected' % err
try: me.address = ''
except AttributeError, err: print 'raised %r as expected' % err
打印结果如下:
中国
Person('Michere', 'Simionato')
Person('Michele', 'Simionato')
raised AttributeError("can't add attribute 'address' to <class '__main__.Person'>",) as expected
raised AttributeError("can't add attribute 'address' to Person('Michele', 'Simionato')",) as expected