这种“下划线”似乎经常出现,我想知道这是Python语言的要求,还是仅仅是一种惯例?

另外,有没有人可以命名并解释哪些函数倾向于有下划线,以及为什么(例如__init__)?


当前回答

在Python中,在函数名中使用下划线表示该函数用于内部使用,不应由用户直接调用。这是一种约定,用于表明函数是“私有的”,而不是模块的公共API的一部分。但是,它不是由语言强制执行的,如果用户选择这样做,仍然可以由用户调用。

其他回答

实际上,当我需要区分父类名和子类名时,我使用_方法名。我读过一些使用这种方式创建父-子类的代码。作为一个例子,我可以提供以下代码:

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))

...

还有带有_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)
    )

...

此约定用于特殊变量或方法(所谓的“魔术方法”),如__init__和__len__。这些方法提供特殊的语法特性或做特殊的事情。

例如,__file__表示Python文件的位置,当a == b表达式执行时执行__eq__。

用户当然可以创建一个自定义的特殊方法,这是非常罕见的情况,但通常可能会修改一些内置的特殊方法(例如,你应该用__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

增加了一个例子来理解__在python中的使用。这里是所有__的列表

https://docs.python.org/3/genindex-all.html#_

某些类型的标识符(除了关键字)具有特殊的 的意思。在任何其他上下文中,任何*名称的使用都不会 遵循明确的文件使用,是受破损没有 警告

使用__的访问限制

"""
Identifiers:
-  Contain only (A-z, 0-9, and _ )
-  Start with a lowercase letter or _.
-  Single leading _ :  private
-  Double leading __ :  strong private
-  Start & End  __ : Language defined Special Name of Object/ Method
-  Class names start with an uppercase letter.
-

"""


class BankAccount(object):
    def __init__(self, name, money, password):
        self.name = name            # Public
        self._money = money         # Private : Package Level
        self.__password = password  # Super Private

    def earn_money(self, amount):
        self._money += amount
        print("Salary Received: ", amount, " Updated Balance is: ", self._money)

    def withdraw_money(self, amount):
        self._money -= amount
        print("Money Withdraw: ", amount, " Updated Balance is: ", self._money)

    def show_balance(self):
        print(" Current Balance is: ", self._money)


account = BankAccount("Hitesh", 1000, "PWD")  # Object Initalization

# Method Call
account.earn_money(100)

# Show Balance
print(account.show_balance())

print("PUBLIC ACCESS:", account.name)  # Public Access

# account._money is accessible because it is only hidden by convention
print("PROTECTED ACCESS:", account._money)  # Protected Access

# account.__password will throw error but account._BankAccount__password will not
# because __password is super private
print("PRIVATE ACCESS:", account._BankAccount__password)

# Method Call
account.withdraw_money(200)

# Show Balance
print(account.show_balance())

# account._money is accessible because it is only hidden by convention
print(account._money)  # Protected Access

双下划线包围的名称对Python来说是“特殊的”。它们在Python语言参考第3节“数据模型”中列出。

来自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. E.g. from M import * does not import objects whose name starts with an underscore. single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g. 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_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

请注意,带有双前导和双尾下划线的名称本质上是为Python本身保留的:“永远不要发明这样的名称;只在文档中使用它们”。