2012-03-03 78 views
0

我注意到,在Python中,一些基本類型有兩種類型的方法:被__包圍的那些和那些不包含的方法。開始和結束的方法___

例如,如果我有稱爲my_numberfloat類型的變量,我可以在IPython中看到,它有下面的方法:

my_number.__abs__   my_number.__pos__ 
my_number.__add__   my_number.__pow__ 
my_number.__class__   my_number.__radd__ 
my_number.__coerce__  my_number.__rdiv__ 
my_number.__delattr__  my_number.__rdivmod__ 
my_number.__div__   my_number.__reduce__ 
my_number.__divmod__  my_number.__reduce_ex__ 
my_number.__doc__   my_number.__repr__ 
my_number.__eq__   my_number.__rfloordiv__ 
my_number.__float__   my_number.__rmod__ 
my_number.__floordiv__  my_number.__rmul__ 
my_number.__format__  my_number.__rpow__ 
my_number.__ge__   my_number.__rsub__ 
my_number.__getattribute__ my_number.__rtruediv__ 
my_number.__getformat__  my_number.__setattr__ 
my_number.__getnewargs__ my_number.__setformat__ 
my_number.__gt__   my_number.__sizeof__ 
my_number.__hash__   my_number.__str__ 
my_number.__init__   my_number.__sub__ 
my_number.__int__   my_number.__subclasshook__ 
my_number.__le__   my_number.__truediv__ 
my_number.__long__   my_number.__trunc__ 
my_number.__lt__   my_number.as_integer_ratio 
my_number.__mod__   my_number.conjugate 
my_number.__mul__   my_number.fromhex 
my_number.__ne__   my_number.hex 
my_number.__neg__   my_number.imag 
my_number.__new__   my_number.is_integer 
my_number.__nonzero__  my_number.real 
  1. 是什麼由___包圍那些之間的差那些不是?
  2. 這是某種標準用於其他編程語言?它是否通常表示類似語言中的相同內容?
+0

可能的重複[下劃線方法是什麼意思?](http://stackoverflow.com/questions/5017282/what-does-underscoring-methods-connote) – 2012-03-03 18:51:15

回答

1

1)你說的變量__ * __是系統變量或方法。

引述的Python參考指南:

System-defined names. These names are defined by the interpreter and its implementation (including the standard library); applications should not expect to define additional names using this convention. The set of names of this class defined by Python may be extended in future versions.

本質上它們被預由系統定義的變量或方法。例如,系統變量__name__可以在任何函數中使用,並且將始終包含該函數的名稱。你可以找到更全面的信息和例子here

2)這個系統保留變量的概念是大多數編程語言的基礎。例如PHP將它們稱爲Magic Constants。使用__FUNCTION__可以在PHP中實現上面獲得函數名的Python示例。更多例子here

3
  1. 通常,「雙下劃線」的方法在內部被Python某些內建函數或運算符使用(例如__add__定義行爲的+)。那些沒有雙下劃線的只是普通的方法,不會被運算符或內建函數使用。現在,這些方法仍然是「正常」方法,因爲您可以像調用其他任何方法一樣調用它們,但Python內核的一部分特別對待它們。
  2. 不,據我所知,這是Python獨有的,雖然許多其他語言支持類似的想法(內建/運算符重載),但通過不同的機制。

無恥插頭:我寫了一個引導到Python的這一方面,去年是相當全面的,你可以閱讀有關如何在http://rafekettler.com/magicmethods.html使用您自己的對象這些方法。

+0

好的,問題:爲什麼我可以做「1」。 __eq __(「2」)=>假,但不是1 .__ eq __(2)=> SyntaxError:語法無效?這個新到Python程序員的驚喜! – 2012-09-04 19:34:14

+0

@MatthewCornell你不能直接在數字(整型或浮點型)文字上調用方法。 '(1).__ eq __(2)'應該有效。 – 2012-09-04 19:47:08

+0

酷!但我不明白。 (1)與1不同?我認爲這是一個運算符優先級問題,例如,在1 .__ eq __(2)的時間段後,解釋器正在尋找更多的問題。從另一個問題來看,1 ..__ eq __(2)*確實起作用。 – 2012-09-04 19:50:41

-2

它用於表示屬性是內部的。在Python中沒有實際的隱私,所以這些被用作提示,指示內部而不是API方法。

+2

如果雙下劃線只是領先的,並且不是尾隨的,則這是正確的。 '__hex'。 – 2012-03-03 18:49:43

1

這些是在特定環境中調用的特殊方法。

Read the documentation for the details.

A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators. For instance, if a class defines a method named __getitem__() , and x is an instance of this class, then x[i] is roughly equivalent to x.__getitem__(i) for old-style classes and type(x).__getitem__(x, i) for new-style classes. Except where mentioned, attempts to execute an operation raise an exception when no appropriate method is defined (typically AttributeError or TypeError).

2

從技術文檔:

Certain classes of identifiers (besides keywords) have special meanings. These classes are identified by the patterns of leading and trailing underscore characters:

_*

Not imported by from module import *. The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the builtin module. When not in interactive mode, _ has no special meaning and is not defined. See section The import statement.

Note The name _ is often used in conjunction with internationalization; refer to the documentation for the gettext module for more information on this convention.

__ * __

System-defined names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of * names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.

__*

Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between 「private」 attributes of base and derived classes. See section Identifiers (Names).

http://docs.python.org/reference/lexical_analysis.html#reserved-classes-of-identifiers

1

要回答你的第二個問題,這個約定是用C使用宏如__FILE__。 Python的創始人Guido van Rossum明確表示這是他在blog on the history of Python中的靈感。