Python中类的对象命名实践
关于如何命名类的对象,我有一个奇怪的问题。
例如,考虑这个类:
>>> class DoSomething:
pass
我应该如何称呼这个类的对象? do_something
还是什么?自从我走出学习阶段以来,我曾经使用 x
、y
或 z
或任何我想到的东西。但现在由于我正在学习编写正确的代码而不是语言,所以我总是面临这个问题。有什么建议吗?
I have this weird problem as to how to name objects of a class.
For example, consider the class:
>>> class DoSomething:
pass
What should I call the object of this class? do_something
or what? Since I came out of the learning stage, I used to use x
, y
or z
or whatever came to my mind. But now since I am learning to write proper code and not the language, I always face this problem. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将其命名为代表其实际用途的名称。例如:
或
Name it something representative of what it's actually being used for. For instance:
or
您应该根据它所代表的内容来命名它。例如,如果我在 Web 应用程序中有一个类
User
,并且我想引用当前登录的用户,我会将变量命名为current_user
。如果您有多个同一类的对象,您的方法会立即失败。为变量提供像
do_something1
、do_something2
这样的索引现在不是也永远不会成为一个选项。使用有意义的内容,以便代码的读者知道该变量代表什么。
顺便提一句。这适用于所有编程语言,而不仅仅是 Python。
You should name it after what it represents. For example if I have a class
User
in a web application and I want to refer to the currently logged-in user, I name the variablecurrent_user
.And if you have more objects of one class, your approach fails immediately. Giving the variable an index like
do_something1
,do_something2
is not and will never be an option.Use something meaningful, so that a reader of your code knows what this variable represents.
Btw. this applies to all programming languages, not just Python.
一种好的命名习惯是为集合(例如集合和列表)提供复数名称。
One good naming practise is to give plural names to collections such as sets and lists.