Python 对象属性 - 访问方法 [英] Python object attributes - methodology for access

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

问题描述

假设我有一个具有某些属性的类.如何最好地(在 Pythonic-OOP 中)访问这些属性?就像 obj.attr 一样?或者写 get 访问器?这些东西的公认命名风格是什么?

Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like obj.attr ? Or perhaps write get accessors ? What are the accepted naming styles for such things ?

您能否详细说明使用单下划线或双前导下划线命名属性的最佳做法?我在大多数模块中看到使用单个下划线.

Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.

如果已经有人问过这个问题(我有一种预感,虽然搜索没有带来结果),请指出它 - 我会关闭这个问题.

If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.

推荐答案

普遍接受的做事方式就是使用简单的属性,就像这样

The generally accepted way of doing things is just using simple attributes, like so

>>> class MyClass:
...     myAttribute = 0
... 
>>> c = MyClass()
>>> c.myAttribute 
0
>>> c.myAttribute = 1
>>> c.myAttribute
1

如果您确实发现自己需要能够编写 getter 和 setter,那么您要查找的是python 类属性"和 Ryan Tomayko 的文章Getters/Setters/Fuxors 是一个很好的起点(虽然有点长)

If you do find yourself needing to be able to write getters and setters, then what you want to look for is "python class properties" and Ryan Tomayko's article on Getters/Setters/Fuxors is a great place to start (albeit a little long)

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

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