2011年4月28日星期四

Variables With Underscores In Python

Python's magical underscored identifiers always surprised me!

__repr__, __unicode__, __str__, __len__, __gt__, __lt__, __eq__, __hash__, __get__, __set__, __getattr__, __setattr__, __del__, __iter__, __next__, __getitem__, __dict__, __blah__

所以……有木有!有木有!!下面讨论的场景主要是在类的定义中。可参见链接[1]。

1. 一个下划线
这是一个约定。使用单个下划线的标识符表示该符号是对象私有的,使用者不应直接操作之。

2. 两个下划线
在类的定义中,如果出现__identifier这样的符号,则不论其所处的语法上下文,都会被符号_classname__identifier代替,其中,classname是去掉下划线的类名。如下例:

>>> def __print_hello():
...     print 'hello'
...
>>> class Class(object):
...     def pack(self):
...             __print_hello()
...
>>> inst = Class()
>>> inst.pack()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in pack
NameError: global name '_Class__print_hello' is not defined
>>>
嗯,我就在第2种情况里挂了一次。。

链接:
[1]. Private Variables,http://docs.python.org/tutorial/classes.html#private-variables
[2]. The meaning of a single- and a double-underscore before an object name in Python,http://stackoverflow.com/questions/1301346/the-meaning-of-a-single-and-a-double-underscore-before-an-object-name-in-python

没有评论:

发表评论