介绍
在本实验中,你将全面了解 Python 中的标识符。你将学习命名 Python 代码中的变量、函数、类和其他对象的根本规则。
通过实践操作,你将能够识别有效和无效的标识符名称,从而巩固命名约定。本实验还将涵盖 Python 中使用的特殊标识符约定,使你掌握编写清晰、可读且易于维护的代码的知识。
在本实验中,你将全面了解 Python 中的标识符。你将学习命名 Python 代码中的变量、函数、类和其他对象的根本规则。
通过实践操作,你将能够识别有效和无效的标识符名称,从而巩固命名约定。本实验还将涵盖 Python 中使用的特殊标识符约定,使你掌握编写清晰、可读且易于维护的代码的知识。
在本步骤中,我们将学习 Python 中标识符的命名规则。标识符是用于在程序中标识变量、函数、类、模块和其他对象的名称。理解命名规则对于编写可读且易于维护的代码至关重要。
正如引言中所述,Python 标识符必须遵循以下规则:
_)。@, %, $, * 等。myVariable 和 myvariable 被视为不同的标识符。让我们创建一个简单的 Python 文件来练习定义一些标识符。
通过点击 Terminal -> New Terminal 打开 WebIDE 中的集成终端。确保你位于 ~/project 目录。
现在,让我们使用 VS Code 编辑器在 ~/project 目录中创建一个名为 identifier_rules.py 的新 Python 文件。你可以通过在左侧文件资源管理器窗格中右键单击并选择 New File 来完成此操作,或者使用命令面板 (Ctrl+Shift+P 或 Cmd+Shift+P) 并输入 File: New File。将文件命名为 identifier_rules.py。
在 identifier_rules.py 文件中,输入以下代码:
## This is a valid identifier
my_variable = 10
## This is also a valid identifier
anotherVariable = "Hello"
## This is a valid identifier starting with an underscore
_private_variable = True
## This is an invalid identifier (starts with a digit)
## 1st_variable = 5
## This is an invalid identifier (contains a space)
## my variable = "invalid"
## This is an invalid identifier (contains a special character)
## my-variable = 20
## This is an invalid identifier (using a keyword)
## if = 30
print(my_variable)
print(anotherVariable)
print(_private_variable)
按 Ctrl+S (或 Cmd+S) 保存文件。
现在,让我们从终端运行此 Python 脚本以查看输出。在终端中,确保你位于 ~/project 目录,并执行以下命令:
python identifier_rules.py
你应该会看到 print 语句的输出,这证实了有效标识符已正确处理。包含无效标识符的行已被注释掉,因此在运行脚本时不会导致错误。
10
Hello
True
这个练习演示了在 Python 中创建有效标识符的基本规则。在接下来的步骤中,我们将更深入地探讨有效和无效标识符以及常见的命名约定。
在本步骤中,我们将根据上一步学到的规则,练习创建 Python 中的有效标识符名称。为变量、函数和其他代码元素选择有意义且有效的名称是编写良好代码的基本组成部分。
让我们使用 VS Code 编辑器在 ~/project 目录中创建一个名为 valid_identifiers.py 的新 Python 文件。
在 valid_identifiers.py 文件中,输入以下代码。此代码使用有效的标识符名称定义了几个变量并打印了它们的值。
## Valid variable names
user_age = 30
total_count = 100
item_price_usd = 25.50
is_active = True
_internal_value = "secret"
MAX_RETRIES = 5
## Valid function name (we will learn about functions later)
def calculate_total():
return user_age * total_count
## Valid class name (we will learn about classes later)
class UserProfile:
def __init__(self, name):
self.name = name
## Print the values of the variables
print("User Age:", user_age)
print("Total Count:", total_count)
print("Item Price (USD):", item_price_usd)
print("Is Active:", is_active)
print("Internal Value:", _internal_value)
print("Maximum Retries:", MAX_RETRIES)
## Call the function and print the result
## print("Calculated Total:", calculate_total())
## Create an instance of the class and print a property
## user = UserProfile("Alice")
## print("User Name:", user.name)
按 Ctrl+S (或 Cmd+S) 保存文件。
现在,让我们从终端运行此 Python 脚本。确保你位于 ~/project 目录,并执行以下命令:
python valid_identifiers.py
你应该会看到变量的值打印到控制台。
User Age: 30
Total Count: 100
Item Price (USD): 25.5
Is Active: True
Internal Value: secret
Maximum Retries: 5
请注意,变量名如何使用下划线 (_) 来分隔单词,这是 Python 中变量和函数名的一种常见约定 (snake_case)。类名,如 UserProfile,通常使用大写字母作为每个单词的首字母 (PascalCase)。常量,如 MAX_RETRIES,通常全部大写并用下划线分隔。
通过这些示例的练习,你将更熟悉在 Python 中创建有效且可读的标识符名称。
在本步骤中,我们将重点识别 Python 中的无效标识符名称。了解什么使标识符无效与知道有效名称的规则同样重要。当你尝试运行 Python 代码时,使用无效标识符会导致 SyntaxError。
让我们使用 VS Code 编辑器在 ~/project 目录中创建一个名为 invalid_identifiers.py 的新 Python 文件。
在 invalid_identifiers.py 文件中,输入以下代码。此代码包含无效标识符名称的示例。我们将故意包含这些示例,以查看它们产生的错误。
## Invalid identifier: starts with a digit
## 1variable = 10
## Invalid identifier: contains a space
## my variable = "hello"
## Invalid identifier: contains a special character (@)
## user@name = "Alice"
## Invalid identifier: contains a special character (-)
## product-id = "XYZ123"
## Invalid identifier: using a Python keyword
## class = "Math"
## Invalid identifier: using another Python keyword
## for = 100
## Invalid identifier: contains a special character ($)
## total$amount = 50.75
## Invalid identifier: contains a special character (%)
## discount%rate = 0.15
print("Attempting to define invalid identifiers will cause a SyntaxError.")
按 Ctrl+S (或 Cmd+S) 保存文件。
现在,让我们尝试从终端运行此 Python 脚本。确保你位于 ~/project 目录,并执行以下命令:
python invalid_identifiers.py
由于所有无效标识符都已注释掉,脚本将成功运行并打印消息。
Attempting to define invalid identifiers will cause a SyntaxError.
现在,让我们取消注释其中一个无效标识符,看看会发生什么错误。删除 ## 1variable = 10 行开头的 #。该行现在应为 1variable = 10。
再次保存文件。
现在,再次运行脚本:
python invalid_identifiers.py
这次,你应该会看到一个 SyntaxError,表明该标识符无效,因为它以数字开头。
File "/home/labex/project/invalid_identifiers.py", line 4
1variable = 10
^
SyntaxError: invalid decimal literal
你可以尝试逐个取消注释其他无效标识符并运行脚本,以查看它们产生的不同类型的 SyntaxError 消息。在取消注释下一个之前,请记住注释掉上一个无效标识符,以隔离错误。
此步骤可帮助你识别命名标识符时的常见错误,并理解遵循命名规则以避免语法错误的重要性。
在本步骤中,我们将探讨 Python 标识符中使用下划线的一些特殊约定。这些约定不一定影响标识符是否根据基本规则有效或无效,但它们传达了有关标识符预期用途或可见性的特定含义。
以下是常见的下划线约定:
_name): 此约定表示该标识符旨在模块或类内部使用。它提示其他程序员不应直接从模块或类外部访问此标识符。但是,Python 不会严格强制执行此规则;如果你选择这样做,仍然可以访问它。__name): 此约定用于类中的名称修饰 (name mangling)。当类中的标识符以两个下划线开头(并且不以两个下划线结尾)时,Python 会在内部更改名称,使其更难直接从类外部访问。这有助于防止继承中的命名冲突。__name__): 这些标识符保留供 Python 解释器特殊使用。例如 __init__(构造函数)、__str__(字符串表示形式)等。除非你正在实现 Python 的特殊方法之一,否则应避免创建具有此模式的自己的标识符。name_): 此约定用于避免与 Python 关键字发生命名冲突。如果你想使用一个 Python 关键字作为名称(例如 class 或 for),你可以附加一个下划线使其成为一个有效的标识符(例如 class_、for_)。让我们使用 VS Code 编辑器在 ~/project 目录中创建一个名为 underscore_conventions.py 的新 Python 文件,以实际演示这些约定。
在 underscore_conventions.py 文件中,输入以下代码:
## Single leading underscore: intended for internal use
_internal_data = "This is internal data"
## Double leading underscore: name mangling in classes
class MyClass:
def __init__(self):
self.__private_attribute = "This is a private attribute"
def get_private_attribute(self):
return self.__private_attribute
## Double leading and trailing underscores: special method
class MyString:
def __init__(self, value):
self.value = value
def __str__(self):
return f"MyString object with value: {self.value}"
## Single trailing underscore: to avoid keyword conflict
import builtins
class_ = "This variable name avoids conflict with the 'class' keyword"
print("Internal data:", _internal_data)
## Accessing the private attribute (demonstrating name mangling)
obj = MyClass()
## print(obj.__private_attribute) ## This will cause an AttributeError
print("Accessing private attribute via method:", obj.get_private_attribute())
## You can technically access it using the mangled name, but it's not recommended
## print("Accessing mangled name:", obj._MyClass__private_attribute)
## Using the special __str__ method
my_str_obj = MyString("Hello World")
print(my_str_obj) ## This calls the __str__ method
print("Variable name avoiding keyword conflict:", class_)
按 Ctrl+S (或 Cmd+S) 保存文件。
现在,从终端运行脚本:
python underscore_conventions.py
你应该会看到演示这些约定的输出。
Internal data: This is internal data
Accessing private attribute via method: This is a private attribute
MyString object with value: Hello World
Variable name avoiding keyword conflict: This variable name avoids conflict with the 'class' keyword
请注意,由于名称修饰,尝试直接访问 obj.__private_attribute 会导致 AttributeError。通过 get_private_attribute 方法或修饰后的名称 _MyClass__private_attribute 访问它也可以工作,但约定是使用该方法。print(my_str_obj) 调用会自动使用 __str__ 方法,因为它是用于字符串表示的特殊方法。
理解这些约定有助于你解读 Python 代码中标识符名称背后的意图,并编写遵循常见实践的代码。
在本实验中,我们学习了 Python 中命名标识符的基本规则。我们练习了使用字母、数字和下划线创建有效的标识符名称,同时遵守标识符不能以数字开头的规则。我们还识别了包含空格、特殊字符或为 Python 关键字的无效标识符名称。此外,我们还探讨了特殊的标识符约定,例如使用前导下划线表示“私有”变量。