常量实例变量? [英] Constant instance variables?
问题描述
我使用@property
来确保对对象实例变量的更改由我需要的方法包装.
I use @property
to ensure that changes to an objects instance variables are wrapped by methods where I need to.
当实例具有逻辑上不应更改的变量时,该怎么办?例如,如果我要为Process创建类,则每个Process实例应具有一个PID属性,该属性将经常访问但不应更改.
What about when an instance has an variable that logically should not be changed? Eg, if I'm making a class for a Process, each Process instance should have a PID attribute that will frequently be accessed but should not be changed.
处理试图修改该实例变量的人的最Pythonic方式是什么?
What's the most Pythonic way to handle someone attempting to modify that instance variable?
-
仅信任用户不要尝试更改 他们不应该的东西吗?
Simply trust the user not to try and change something they shouldn't?
使用属性,但引发一个 如果实例变量是 变了吗?
Use property but raise an exception if the instance variable is changed?
还有什么?
推荐答案
使用__
前缀变量的名称,并创建只读属性,Python将处理异常,并且变量本身将受到保护,以防止意外覆盖
Prepend name of the variable with __
, and create read-only property, Python will take care of exceptions, and variable itself will be protected from accidental overwrite.
class foo(object):
def __init__(self, bar):
self.__bar = bar
@property
def bar(self):
return self.__bar
f = foo('bar')
f.bar # => bar
f.bar = 'baz' # AttributeError; would have to use f._foo__bar
这篇关于常量实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!