Python 只读属性 [英] Python read-only property

查看:67
本文介绍了Python 只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道什么时候属性应该是私有的,我是否应该使用属性.

我最近读到 setter 和 getter 不是 Pythonic,我应该使用属性装饰器.没关系.

I read recently that setters and getters are not pythonic and I should use property decorator. It's ok.

但是如果我有属性,它不能从类外部设置但可以读取(只读属性)怎么办.这个属性应该是私有的吗?私有我的意思是带下划线,比如 self._x?如果是,那么如何在不使用 getter 的情况下阅读它?我现在知道的唯一方法就是写

But what if I have attribute, that mustn't be set from outside of class but can be read (read-only attribute). Should this attribute be private, and by private I mean with underscore, like that self._x? If yes then how can I read it without using getter? Only method I know right now is to write

@property
def x(self):
    return self._x

这样我就可以通过 obj.x 读取属性,但是我不能设置它 obj.x = 1 所以没问题.

That way I can read attribute by obj.x but I can't set it obj.x = 1 so it's fine.

但是我真的应该关心设置不能设置的对象吗?也许我应该离开它.但是我又不能使用下划线,因为读取 obj._x 对用户来说很奇怪,所以我应该使用 obj.x 然后用户不知道他不得设置此属性.

But should I really care about setting object that mustn't be set? Maybe I should just leave it. But then again I can't use underscore because reading obj._x is odd for user, so I should use obj.x and then again user doesn't know that he mustn't set this attribute.

你有什么看法和做法?

推荐答案

通常,编写 Python 程序时应该假设所有用户都是成年人同意的,因此他们有责任自己正确使用事物.但是,在极少数情况下,属性可设置(例如派生值,或从某些静态数据源读取的值)没有意义,只有 getter 属性通常是首选模式.

Generally, Python programs should be written with the assumption that all users are consenting adults, and thus are responsible for using things correctly themselves. However, in the rare instance where it just does not make sense for an attribute to be settable (such as a derived value, or a value read from some static datasource), the getter-only property is generally the preferred pattern.

这篇关于Python 只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆