简体   繁体   English

Python-如何创建在__init__期间可配置的不可变类成员

[英]Python - how to create immutable class member that is configurable during __init__

I would like to create a class member that can be assigned a user-specified value by the constructor, but could not be changed afterwards. 我想创建一个类成员,该成员可以由构造函数分配一个用户指定的值,但此后不能更改。 Is there a way to do this? 有没有办法做到这一点?

So far I have gotten the following code, which mostly works but is not "idiot proof". 到目前为止,我已经获得了以下代码,该代码通常有效,但不是“白痴证明”。

def constantify(f):
    def fset(self, value):
        raise SyntaxError ('Not allowed to change value')
    def fget(self):
        return f(self)
    return property(fget, fset)

class dummy(object):
    def __init__(self,constval):
        self.iamvar = None
        self._CONST = constval

    @constantify
    def SOMECONST(self):
        return self._CONST


dum = dummy(42)
print 'Original Val:', dum.SOMECONST

this prints "Original Val: 42" 这打印“原始Val:42”

dum.SOMECONST = 24 

This gives the correct SyntaxError 这给出了正确的SyntaxError

But, enter an idiot, 但是,输入一个白痴,

dum._CONST = 0
print 'Current Val:', dum.SOMECONST

gives "Current Val: 0" 给出“当前值:0”

Is there a better idiot-proof way of achieving this? 有没有更好的防白痴方法来实现这一目标?

Or is it the case that an class member that is initializable but remains const afterwards is somehow not a "pythonic" way? 还是可初始化但之后仍保持const的类成员某种程度上不是“ pythonic”方式? (I'm still a newbie learning the pythonic way) In that case, What would be a pythonic way of creating a class for which each instance is "configurable" at the time of instantiation only? (我仍然是学习pythonic方式的新手)在那种情况下,创建仅实例化时每个实例都是“可配置”的类的pythonic方式是什么?

Kalpit 卡尔皮特

Update : I don't want to create a class for which all the members are immutable. 更新 :我不想创建一个所有成员都是不可变的类。 I only want some members to be constant, and others variable at any time. 我只希望某些成员保持不变,而其他成员则随时可变。

The simplest way I could think of, is to override the __setattr__ and raise an Error whenever the particular attribute is set, like this 我能想到的最简单的方法是,重写__setattr__并在设置了特定属性时引发一个错误,就像这样

class dummy(object):
    def __init__(self, arg):
        super(dummy, self).__setattr__("data", arg)

    def __setattr__(self, name, value):
        if name == "data":
            raise AttributeError("Can't modify data")
        else:
            super(dummy, self).__setattr__(name, value)

a = dummy(5)
print a.data
# 5
a.data = "1"
# AttributeError: Can't modify data

One nice thing about collections.namedtuple is that you can derive another class from an instance of it: 关于collections.namedtuple一件好事是,您可以从其实例派生另一个类:

from collections import namedtuple

class Foo(namedtuple('Foo', ['a', 'b'])):
    def __new__(cls, a, b, *args, **kwargs):
        return super(Foo, cls).__new__(cls, a, b)

    def __init__(self, a, b, c):
        # a & b are immutable and handled by __new__
        self.c = c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM