简体   繁体   中英

Enforcing selected immutability in Python

I'd like to be able to declare specific variables and objects immutable. (The problem arises when object instance variables, which should be treated as immutable, can be changed.) One thought is to use named tuples.

from collections import namedtuple


C_tuple = namedtuple('C_tuple', 'a b c')
class C:

    def __init__(self, a, b, c):
        self.c_tuple = C_tuple(a=a, b=b, c=c)

    @property
    def a(self):
        return self.c_tuple.a

    @property
    def b(self):
        return self.c_tuple.b

    @property
    def c(self):
    return self.c_tuple.c

c = C(1, 2, 3)
print(c.a, c.b, c.c)   # ==> `1 2 3`

(I have not been able to find a way to declare C_tuple within the C class. Even with from __future__ import annotations I still get an error.)

Is there a better approach?

Thanks.

When you are defining the class I think you're defining the variable a,b,c referring to themselves.

def __init__(self, a, b, c):
    self.c_tuple = C_tuple(a='a', b='b', c='c')

Also, You're missing indentation in line number 20.

@property
def c(self):
    return self.c_tuple.c

Please feel free to correct me as namedtuples are a completely new topic for me:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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