Python中的“單下劃線”和“雙下劃線”變量的含義和區別

想要知道Python中的“單下劃線”和“雙下劃線”變量的含義和區別嗎,請看下面的解釋

private – The meaning of a single- and a double-underscore before an object name in Python – Stack Overflow.

 

Single Underscore

Names, in a class, with a leading underscore are simply to indicate to other programmers that the attribute or method is intended to be private. However, nothing special is done with the name itself.

To quote PEP-8:

_single_leading_underscore: weak “internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

Double Underscore (Name Mangling)

From the Python docs:

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

And a warning from the same page:

Name mangling is intended to give classes an easy way to define “private” instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private.

Example

>>>classMyClass():...def __init__(self):...self.__superprivate ="Hello"...self._semiprivate =", world!"...>>> mc =MyClass()>>>print mc.__superprivate
Traceback(most recent call last):File"<stdin>", line 1,in<module>AttributeError: myClass instance has no attribute '__superprivate'>>>print mc._semiprivate
, world!>>>print mc.__dict__
{'_MyClass__superprivate':'Hello','_semiprivate':', world!'}

 

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s

%d 位部落客按了讚: