Tekkaman

导航

 

python之private variables

  “Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

  Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. 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, as long as it occurs within the definition of a class.

  Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls. For example:

  

 [demo]

1 class Point:
2   def __init__(self):
3     self.__count = 10; 
4   def __show(self):
5     print 'Hello world'
6   
7 pt = Point()
8 print pt._Point__count
9 pt._Point__show()

        上例可以看到, 直接调用 pt.__count || pt.__show() 会发现找不到属性, 必须加上 _Point前缀才行.

posted on 2013-10-11 10:07  Tekkaman  阅读(968)  评论(0编辑  收藏  举报