为什么某些函数在函数名称前后都有下划线“ __”?

本文翻译自: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节“数据模型”中列出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值