阻止在__init__外部创建新属性 [英] Prevent creating new attributes outside __init__

查看:97
本文介绍了阻止在__init__外部创建新属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要能够创建一个使用 __ init __ 初始化的类(在Python中),不接受新属性,但接受对现有属性的修改。有几种方法我可以看到这样做,例如有一个 __ setattr __ 方法如

I want to be able to create a class (in Python) that once initialized with __init__, does not accept new attributes, but accepts modifications of existing attributes. There's several hack-ish ways I can see to do this, for example having a __setattr__ method such as

def __setattr__(self, attribute, value):
    if not attribute in self.__dict__:
        print "Cannot set %s" % attribute
    else:
        self.__dict__[attribute] = value

然后编辑 __ dict__ 直接在 __ init __ 里,但我想知道是否有一个正确的方法来做到这一点?

and then editing __dict__ directly inside __init__, but I was wondering if there is a 'proper' way to do this?

推荐答案

我不会直接使用 __ dict __ ,但你可以添加一个函数来显式冻结

I wouldn't use __dict__ directly, but you can add a function to explicitly "freeze" a instance:

class FrozenClass(object):
    __isfrozen = False
    def __setattr__(self, key, value):
        if self.__isfrozen and not hasattr(self, key):
            raise TypeError( "%r is a frozen class" % self )
        object.__setattr__(self, key, value)

    def _freeze(self):
        self.__isfrozen = True

class Test(FrozenClass):
    def __init__(self):
        self.x = 42#
        self.y = 2**3

        self._freeze() # no new attributes after this point.

a,b = Test(), Test()
a.x = 10
b.z = 10 # fails

这篇关于阻止在__init__外部创建新属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆