常量实例变量?

发布于 2024-08-06 08:24:35 字数 295 浏览 2 评论 0原文

我使用 @property 来确保对对象实例变量的更改由我需要的方法包装。

当实例具有逻辑上不应更改的变量时该怎么办?例如,如果我正在为 Process 创建一个类,则每个 Process 实例都应该有一个经常被访问但不应更改的 PID 属性。

处理试图修改实例变量的人的最 Pythonic 方法是什么?

  • 简单地相信用户不会尝试改变 他们不应该做的事?

  • 使用财产但提出 如果实例变量是异常 改变了?

  • 还有什么吗?

I use @property to ensure that changes to an objects instance variables are wrapped by methods where I need to.

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.

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?

  • Something else?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

忘你却要生生世世 2024-08-13 08:24:35

在变量名称前面添加 __,并创建只读属性,Python 将处理异常,并且变量本身将受到保护,不会被意外覆盖。

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

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
莫言歌 2024-08-13 08:24:35

简单地信任用户并不一定是坏事;如果您只是编写一个快速的 Python 程序,用一次就扔掉,您很可能只是相信用户不会更改 pid 字段。

恕我直言,强制执行只读字段的最 Pythonic 方法是使用在尝试设置字段时引发异常的属性。

所以,恕我直言,你对这些东西有很好的直觉。

Simply trusting the user is not necessarily a bad thing; if you are just writing a quick Python program to be used once and thrown away, you might very well just trust that the user not alter the pid field.

IMHO the most Pythonic way to enforce the read-only field is to use a property that raises an exception on an attempt to set the field.

So, IMHO you have good instincts about this stuff.

心不设防 2024-08-13 08:24:35

也许你可以覆盖__setattr__?在行中,

def __setattr__(self, name, value):
    if self.__dict__.has_key(name):
        raise TypeError, 'value is read only'
    self.__dict__[name] = value

Maybe you can override __setattr__? In the line of,

def __setattr__(self, name, value):
    if self.__dict__.has_key(name):
        raise TypeError, 'value is read only'
    self.__dict__[name] = value
骄傲 2024-08-13 08:24:35

只需使用一个属性和一个隐藏属性(以下划线前缀)。

简单属性是只读的!

>>> class Test (object):
...  @property
...  def bar(self):
...   return self._bar
... 
>>> t = Test()
>>> t._bar = 2
>>> t.bar
2
>>> t.bar = 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

使用双下划线隐藏并不是为了隐藏实现,而是为了确保不会与子类的属性发生冲突;以 mixin 为例,它必须非常小心!

如果您只想隐藏该属性,请使用单个下划线。正如您所看到的,没有额外的魔法需要添加 - 如果您没有定义集合函数,您的属性就像方法的返回值一样只读。

Simply use a property and a hidden attribute (prefixed with one underscore).

Simple properties are read-only!

>>> class Test (object):
...  @property
...  def bar(self):
...   return self._bar
... 
>>> t = Test()
>>> t._bar = 2
>>> t.bar
2
>>> t.bar = 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

Hiding with double underscore is not used to hide the implementation, but to make sure you don't collide with a subclass' attributes; consider a mixin for example, it has to be very careful!

If you just want to hide the attribute, use a single underscore. And as you see there is no extra magic to add -- if you don't define a set function, your property is just as read-only as the return value of a method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文