您可以使用上面貼了答案,但對於更多的「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) –