Confused with Underscores in Python

A

abhay

Hi,

I'm a python newbie with an utmost zeal to master the language.
I have really not understood the concept of underscores used in some of the
methods in python. Is it somewhat smilar to declaring public, private or
protected methods as in java.
Any help is most welcomed.

Abhay
 
S

Scott David Daniels

abhay said:
I have really not understood the concept of underscores used in some of the
methods in python. Is it somewhat smilar to declaring public, private or
protected methods as in java.

In a way. Python's "magic" names (those treated specially by the
system) both begin and end with double-underscores. This rule is
to allow Python's evolution as a language without interfereing with
user-defined names. The "next" method on iterators should probably
have been "__next__".

A single underscore following a name is used for names that would
naturally be a keyword (class_ for class, for example).

In a class, a method name beginning with a single underscore is a
method is means roughly, "this is an internal method (or variable),
not an interface method. Don't expect this to work the same way or
even exist in the next version."

A name beginning with a single underscore means roughly, "this is an
internal function, method, or variable, not an interface method. Don't
expect this to work the same way or even exist in the next version."

In a class, a method or variable name beginning with a double-underscore
(and not ending with a double-underscore) is meant to be class-local.
These names are useful primarily to avoid name conflicts with super-
and sub- classes, as in the cases of "mixin" style programming.
Some programmers use this as a means to "enforce" privacy, but it
really doesn't work -- it is easy to defeat if you care to, and a
single initial underscore should be enough to warn off those who will
cooperate.

-Scott David Daniels
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top