您可以使用上面贴了答案,但对于更多的“Python化”的做法,尝试(链接到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
你为什么要这个? – Dhara
你为什么想要做这样的事情? –
@mattwritescode,Dhara:在某些情况下使用'__slots__'可以使代码更快。除此之外,它可以强制执行某些OOP操作。看到[这里](http://stackoverflow.com/questions/472000/python-slots) –