what is the difference between name and _name?

Steven D'Aprano steve at pearwood.info
Wed Aug 20 04:49:04 EDT 2014


On Wed, 20 Aug 2014 15:16:56 +0800, luofeiyu wrote:

> When i learn property in python , i was confused by somename and
> _somename,what is the difference between them?

One name starts with underscore, the other does not. In names, an 
underscore is just a letter with no special meaning:

foo, bar, foo_bar, spam, spam2, spam_with_eggs ...

But Python has some naming conventions:

(1) Names with TWO underscores at the start and end of the name are 
reserved for Python: __dict__ __add__ __str__ etc. all have special 
meaning to Python.

(2) Names with ONE leading underscore are intended as "private" variables 
or names, the caller should not use it.

So in this example:

> class Person(object):
>      def __init__(self, name):
>          self._name = name
       [...]
>      name = property(getName, setName, delName, "name property docs")

(1) __init__ is a "dunder" (Double UNDERscore) name, and is special to 
Python. It is used for the initialiser method;

(2) _name is a single underscore "private" attribute, only the Person 
class is supposed to use it; and

(3) name is the public attribute that other classes or functions are 
permitted to use.


Unless the documentation for the class or library says different, you 
should ignore any _single underscore methods and attributes. They are 
private, and subject to change without warning.



-- 
Steven



More information about the Python-list mailing list