ZetCode

Python 变量

最后修改日期:2025 年 2 月 26 日

Python 中的变量用于存储可以在程序中引用和操作的数据。Python 支持各种类型的变量,包括绑定/未绑定、静态、类和实例变量。本教程涵盖了变量使用的不同上下文以及实际示例。

变量是引用存储在内存中的值的名称。它们允许我们在程序中存储和操作数据。Python 变量不需要显式声明,并且可以动态更改类型。变量可以根据其作用域和上下文进行分类,例如局部、全局、类和实例变量。

模块变量

在 Python 中,模块变量是在模块(`.py` 文件)顶层定义的变量。这些变量可以从模块的任何部分访问,也可以导入到其他模块。

关键特征

让我们考虑一个名为 `example_module.py` 的模块

example_module.py
# Module variables 
PI = 3.14159 
E = 2.71828

# Function that uses module variables 
def calculate_circle_area(radius): 
    return PI * radius * radius

# Class that uses module variables 
class MathConstants: 

    def get_constants(self):
        return PI, E

在此示例中,`PI` 和 `E` 是模块变量。`calculate_circle_area` 函数和 `get_constants` 方法使用这些模块变量。

我们可以将这些模块变量导入到另一个模块或脚本中

main.py
from example_module import PI, E

print(f'The value of PI is: {PI}') 
print(f'The value of E is:{E}')

在这种情况下,`PI` 和 `E` 从 `example_module` 导入,并可以在 `another_module` 中使用。

绑定和未绑定变量

此示例演示了 Python 中的绑定和未绑定变量。

bound_unbound.py
x = 10  # Bound variable (assigned a value)

def my_function():
    print(y)  # Unbound variable (not assigned a value)

# my_function()  # Uncommenting this line will raise a NameError

绑定变量是已分配值的变量,例如 `x`。未绑定变量是未分配值的变量,例如 `my_function` 中的 `y`。访问未绑定变量会引发 `NameError`。

函数作用域变量

此示例演示了 Python 中的函数作用域变量。

static_variable.py
def my_function():
    if not hasattr(my_function, "counter"):
        my_function.counter = 0  # Static variable
    my_function.counter += 1
    return my_function.counter

print(my_function())  # Output: 1
print(my_function())  # Output: 2
print(my_function())  # Output: 3

函数作用域变量在函数调用之间保留其状态。

类变量

此示例演示了 Python 中的类变量。

class_variable.py
class MyClass:
    class_var = 10  # Class variable

print(MyClass.class_var)  # Output: 10

obj1 = MyClass()
obj2 = MyClass()

print(obj1.class_var)  # Output: 10
print(obj2.class_var)  # Output: 10

MyClass.class_var = 20  # Modify class variable
print(obj1.class_var)  # Output: 20
print(obj2.class_var)  # Output: 20

类变量是类所有实例共享的变量。它在类内定义,但在任何方法之外。类变量使用类名或类的实例进行访问。

实例变量

此示例演示了 Python 中的实例变量。

instance_variable.py
class MyClass:
    def __init__(self, value):
        self.instance_var = value  # Instance variable

obj1 = MyClass(10)
obj2 = MyClass(20)

print(obj1.instance_var)  # Output: 10
print(obj2.instance_var)  # Output: 20

obj1.instance_var = 30
print(obj1.instance_var)  # Output: 30
print(obj2.instance_var)  # Output: 20

实例变量是类每个实例唯一的变量。它在 `__init__` 方法或其他实例方法内定义。实例变量使用实例名称进行访问。

全局变量

此示例演示了 Python 中的全局变量。

global_variable.py
x = 10  # Global variable

def my_function():
    global x  # Declare x as global
    x = 20
    print(f"Inside function: {x}")

my_function()
print(f"Outside function: {x}")

# Output:
# Inside function: 20
# Outside function: 20

全局变量是在任何函数或类外部定义的变量,可以在整个程序中访问。要在函数内修改全局变量,请使用 `global` 关键字。

局部变量

此示例演示了 Python 中的局部变量。

local_variable.py
def my_function():
    x = 10  # Local variable
    print(f"Inside function: {x}")

my_function()
# print(x)  # Uncommenting this line will raise a NameError

# Output:
# Inside function: 10

局部变量是在函数或块内定义的变量,并且只能在其作用域内访问。尝试在作用域外访问局部变量会引发 `NameError`。

使用变量的最佳实践

来源

Python 作用域和命名空间文档

在本文中,我们探讨了 Python 变量,并通过实际示例演示了它们在不同上下文中的用法。

作者

我的名字是 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有超过十年的经验。

列出所有 Python 教程