您可以使用上面发布的答案,但对于更“pythonic”的方法,请尝试(链接到 code.activestate.com)中列出的方法
以供将来参考,在我弄清楚如何链接到该网站之前,代码如下:
def frozen(set):
"""Raise an error when trying to set an undeclared name, or when calling
from a method other than Frozen.__init__ or the __init__ method of
a class derived from Frozen"""
def set_attr(self,name,value):
import sys
if hasattr(self,name): #If attribute already exists, simply set it
set(self,name,value)
return
elif sys._getframe(1).f_code.co_name is '__init__': #Allow __setattr__ calls in __init__ calls of proper object types
for k,v in sys._getframe(1).f_locals.items():
if k=="self" and isinstance(v, self.__class__):
set(self,name,value)
return
raise AttributeError("You cannot add attributes to %s" % self)
return set_attr