HOWTO · Python

Python 中函数、类、常量和变量的命名约定

了解用于命名 Python 中的函数、类、常量和变量的最佳命名约定

本页内容

PEP 8 或 Python Enhancement Proposal 8 是编写 Python 代码的指南和最佳实践指南。这些指南旨在提高 Python 代码库的可读性、理解力和一致性。由于 PEP 8 有一个标准并且主要在行业和专业人士中使用,因此初学者最好坚持使用它,因为几乎所有的 Python 代码库都使用它,并且在新添加的代码中使用它可以促进向后兼容编码。

PEP 8 还讨论了用于在 Python 中命名变量、函数、常量和类的命名约定。本文将讨论这些约定以及一些相关示例。

Python 中函数的命名约定

PEP 8 建议使用由下划线分隔的小写单词来命名函数。例如,hello_worldcomputer_sciencesend_mail_to_userget_updates_from_userdelete_all_users 等。

def hello_world():
    pass


def computer_science():
    pass


def send_mail_to_user():
    pass


def get_updates_from_user():
    pass


def delete_all_users():
    pass

Python 类的命名约定

PEP 8 建议使用 Upper Camel Case 或 Pascal Case 来命名类。例如,PersonHelloWorldHumanPythonIsFunMyCustomClass 等。

class Person:
    pass


class HelloWorld:
    pass


class Human:
    pass


class PythonIsFun:
    pass


class MyCustomClass:
    pass

Python 中常量的命名约定

PEP 8 建议使用下划线分隔的大写单词来命名常量。例如,HELLO_WORLDCOMPUTER_SCIENCENUMBER_OF_USERSEMAIL_LIMITEMAIL_USERNAME 等。

HELLO_WORLD = "A string"
COMPUTER_SCIENCE = "A subject"
NUMBER_OF_USERS = 450
EMAIL_LIMIT = 100
EMAIL_USERNAME = "vaibhav"

Python 中变量的命名约定

PEP 8 建议使用由下划线分隔的小写单词来命名变量。例如,hello_worldcomputer_sciencenumber_of_usersemail_limitemail_username 等。

hello_world = "A string"
computer_science = "A subject"
number_of_users = 450
email_limit = 100
email_username = "vaibhav"