views:

65

answers:

3

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?

+4  A: 

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)
Amber
Aah I see. This approach is also useful.
A A
+2  A: 

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.

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.

Felix Kling
I see. Thanks for the information.
A A
A: 

One good naming practise is to give plural names to collections such as sets and lists.

Tony Veijalainen