简体   繁体   English

Python中类对象的命名实践

[英]Naming practice for objects of a class in Python

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? do_something还是什么? Since I came out of the learning stage, I used to use x , y or z or whatever came to my mind. 自从进入学习阶段以来,我曾经使用过xyz或任何我想到的东西。 But now since I am learning to write proper code and not the language, I always face this problem. 但是现在,由于我正在学习编写正确的代码而不是语言,所以我总是会遇到这个问题。 Any suggestions? 有什么建议么?

Name it something representative of what it's actually being used for. 为其命名,以代表其实际用途。 For instance: 例如:

class Cereal:
    def eat(self):
        print 'yum'

breakfast = Cereal()
breakfast.eat()

or 要么

class User:
    def __init__(self, userid):
        # ...

admin_user = User(ADMIN_ID)

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 variable current_user . 例如,如果我在Web应用程序中有一个User类,并且想引用当前登录的用户,则将变量命名为current_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 . 给该变量一个索引,例如do_something1do_something2 不是并且永远不会是一个选择

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. 这适用于所有编程语言,而不仅仅是Python。

一种好的命名习惯是为集合(例如集合和列表)赋予复数名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM