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

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

问题描述

我希望能够创建一个类(在 Python 中),一旦用 __init__ 初始化,它不接受新属性,但接受现有属性的修改.我可以看到几种hack-ish方法来做到这一点,例如有一个 __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

然后直接在 __init__ 中编辑 __dict__,但我想知道是否有正确"的方法来做到这一点?

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天全站免登陆