爲什麼某些函數在函數名稱前後都有下劃線“ __”?

本文翻譯自:Why do some functions have underscores “__” before and after the function name?

This seems to occur a lot, and was wondering if this was a requirement in the Python language, or merely a matter of convention? 這似乎經常發生,並且想知道這是否是Python語言中的要求,還是僅出於約定?

Also, could someone name and explain which functions tend to have the underscores, and why ( __init__ , for instance)? 另外,有人可以說出並解釋哪個函數傾向於帶有下劃線嗎?爲什麼(例如__init__ )?


#1樓

參考:https://stackoom.com/question/aSei/爲什麼某些函數在函數名稱前後都有下劃線


#2樓

Actually I use _ method names when I need to differ between parent and child class names. 實際上,當我需要在父類和子類名稱之間進行區分時,我使用_方法名稱。 I've read some codes that used this way of creating parent-child classes. 我已經閱讀了一些使用這種方法創建父子類的代碼。 As an example I can provide this code: 例如,我可以提供以下代碼:

class ThreadableMixin:
   def start_worker(self):
       threading.Thread(target=self.worker).start()

   def worker(self):
      try:
        self._worker()
    except tornado.web.HTTPError, e:
        self.set_status(e.status_code)
    except:
        logging.error("_worker problem", exc_info=True)
        self.set_status(500)
    tornado.ioloop.IOLoop.instance().add_callback(self.async_callback(self.results))

... ...

and the child that have a _worker method 和具有_worker方法的孩子

class Handler(tornado.web.RequestHandler, ThreadableMixin):
   def _worker(self):
      self.res = self.render_string("template.html",
        title = _("Title"),
        data = self.application.db.query("select ... where object_id=%s", self.object_id)
    )

... ...


#3樓

This convention is used for special variables or methods (so-called “magic method”) such as__init__ , len . 此約定用於特殊變量或方法(所謂的“魔術方法”),例如__init__, len These methods provides special syntactic features or does special things. 這些方法提供特殊的語法功能或執行特殊的操作。

For example, file indicates the location of Python file, eq is executed when a == b expression is excuted. 例如, file表示Python文件的位置,當執行a == b表達式時執行eq

A user of course can make custom special method, it is very rare case, but often might modify the some built-in special methods. 用戶當然可以製作自定義的特殊方法,這種情況很少見,但經常可能會修改一些內置的特殊方法。 (eg You should initialize the class with init that will be executed at first when a instance of class is created.) (例如,您應該使用將在創建類實例時首先執行的init初始化類。)

   class A:
      def __init__(self, a): # use special method '__init__' for initializing
        self.a = a
      def __custom__(self): # custom special method. you might almost do not use it
        pass

#4樓

Rear Double Underscore (Name Mangling)/ From the Python Docs 後雙重下劃線(名稱管理)/來自Python文檔

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. 形式__spam的任何標識符(至少兩個前導下劃線,最多一個尾隨下劃線)在文本上用_classname__spam替換,其中classname是當前類名,其中前導下劃線被剝離。 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. 在其他類的實例上對此類私有。

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. 確定的靈魂仍然可以訪問或修改被視爲私有的變量。


#5樓

From the Python PEP 8 -- Style Guide for Python Code : Python PEP 8-Python代碼樣式指南

Descriptive: Naming Styles 描述性:命名樣式

The following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention): 可以識別以下使用前劃線或後劃線的特殊形式(通常可以將它們與任何大小寫慣例結合使用):

  • _single_leading_underscore : weak "internal use" indicator. _single_leading_underscore :“內部使用”指標較弱。 Eg from M import * does not import objects whose name starts with an underscore. 例如, from M import *不會導入名稱以下劃線開頭的對象。

  • single_trailing_underscore_ : used by convention to avoid conflicts with Python keyword, eg single_trailing_underscore_ :約定用於避免與Python關鍵字衝突,例如

    Tkinter.Toplevel(master, class_='ClassName')

  • __double_leading_underscore : when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo ; see below). __double_leading_underscore :命名類屬性時,調用名稱修飾(在類FooBar中, __boo變爲_FooBar__boo ;請參見下文)。

  • __double_leading_and_trailing_underscore__ : "magic" objects or attributes that live in user-controlled namespaces. __double_leading_and_trailing_underscore__ :存在於用戶控制的名稱空間中的“魔術”對象或屬性。 Eg __init__ , __import__ or __file__ . 例如__init____init__ __import____file__ Never invent such names; 請勿發明此類名稱; only use them as documented. 僅按記錄使用它們。

Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented". 請注意,帶有雙引號和尾部下劃線的名稱本質上是爲Python本身保留的:“切勿發明此類名稱;僅將其用作文檔”。


#6樓

Names surrounded by double underscores are "special" to Python. 帶有雙下劃線的名稱是Python的“特殊”名稱。 They're listed in the Python Language Reference, section 3, "Data model" . 它們在Python語言參考的第3節“數據模型”中列出。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章