问题描述
假设我有一些属性的类。它是如何最好(在Python化,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类属性,的是一个伟大的地方开始(虽然有点长)
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 onGetters/Setters/Fuxors is a great place to start (albeit a little long)
这篇关于Python对象属性 - 方法访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!