Keep the lifespan of variable after multiple function calls?

后端 未结 4 1177
抹茶落季
抹茶落季 2021-01-27 17:18

Assuming:

def myfunc(x):
    my_list  = []
    list.append(x)

is there a keyword to stop a variable(my_list) from being reassigned? Let\'s supp

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-27 18:03

    I guess you are looking for something equivalent to the final keyword in Java. Simply put, there is no such keyword. The Python attitude is "if you don't want this modified at all, just don't modify it, I wont stop you though".

    However you can mimic something like it by some tweaks in your class.

    class MyFinalVariablesClass:
        def __setattr__(self, attr, value):
            # if it already has this attribute, complain !
            if hasattr(self, attr):
                raise Exception("Attempting to alter read-only value")
    
            self.__dict__[attr] = value
    

    Or in the case of your variable (haven't tested it)

    class WriteOnceReadWhenever:
        def __setattr__(self, attr, value):
            if attr == 'my_list' and hasattr(self, attr):
                raise Exception("Attempting to alter read-only value")
            self.__dict__[attr] = value
    

提交回复
热议问题