常量实例变量?
我使用 @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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在变量名称前面添加
__
,并创建只读属性,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.简单地信任用户并不一定是坏事;如果您只是编写一个快速的 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.
也许你可以覆盖
__setattr__
?在行中,Maybe you can override
__setattr__
? In the line of,只需使用一个属性和一个隐藏属性(以下划线前缀)。
简单属性是只读的!
使用双下划线隐藏并不是为了隐藏实现,而是为了确保不会与子类的属性发生冲突;以 mixin 为例,它必须非常小心!
如果您只想隐藏该属性,请使用单个下划线。正如您所看到的,没有额外的魔法需要添加 - 如果您没有定义集合函数,您的属性就像方法的返回值一样只读。
Simply use a property and a hidden attribute (prefixed with one underscore).
Simple properties are read-only!
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.