我要尋找在python的方式來建立Python類是:不可改變的屬性
- 二傳手分配前檢查值的類型
- 不可能增加新的類屬性
暫時我發現,這兩項裝飾:
def getter_setter_gen(name, type_): def getter(self): return getattr(self, "__" + name) def setter(self, value): print "setter", value if not isinstance(value, type_): raise TypeError("%s attribute must be set to an instance of %s" % (name, type_)) setattr(self, "__" + name, value) return property(getter, setter) def auto_attr_check(cls): new_dct = {} print "auto_attr_check", cls.__dict__.items() for key, value in cls.__dict__.items(): if isinstance(value, type): value = getter_setter_gen(key, value) new_dct[key] = value # Creates a new class, using the modified dictionary as the class dict: n = type(cls)(cls.__name__, cls.__bases__, new_dct) return n
和
def froze_it(cls): def frozensetattr(self, key, value): print key key = ''+key print(dir(self)) print key if not hasattr(self, key): raise TypeError("Class {} is frozen. Cannot set {} = {}" .format(cls.__name__, key, value)) else: object.__setattr__(self, key, value) cls.__setattr__ = frozensetattr return cls
但我有很多麻煩加入這兩種方法。 你能幫我嗎?你有想法嗎? 非常感謝