Python 基础与进阶概念详解
1. @classmethod
、@staticmethod
和 @property
分别是什么
这三个是 Python 中常用的装饰器,用于类和对象的行为定义。
@classmethod
@classmethod
装饰器将方法绑定到类而不是实例,方法的第一个参数是类本身(通常命名为cls
)。它可以用来定义类级别的操作。
python
class MyClass:
class_variable = "I am a class variable"
@classmethod
def class_method(cls):
return f"This is a class method. Class variable: {cls.class_variable}"
print(MyClass.class_method()) # 输出: This is a class method. Class variable: I am a class variable
@staticmethod
@staticmethod
装饰器定义一个静态方法,它不绑定到类或实例,也没有默认的self
或cls
参数。适合定义与类逻辑相关但不需要访问类或实例状态的工具函数。
python
class MyClass:
@staticmethod
def static_method(x, y):
return x + y
print(MyClass.static_method(3, 5)) # 输出: 8
@property
@property
装饰器将方法伪装成属性,允许你以属性的方式访问它。通常用于 getter、setter 或 deleter。
python
class MyClass:
def __init__(self):
self._value = 10
@property
def value(self):
return self._value
@value.setter
def value(self, new_value):
self._value = new_value
obj = MyClass()
print(obj.value) # 输出: 10
obj.value = 20
print(obj.value) # 输出: 20
2. 什么是 Lambda 函数,有什么好处
Lambda 函数是 Python 中的匿名函数,使用 lambda
关键字定义。它通常用于短小的、一次性的函数定义。
- 语法 :
lambda arguments: expression
- 好处 :
- 简洁:适合用在需要函数但不想定义完整函数的场景。
- 可作为参数传递:常用于高阶函数(如
map()
、filter()
)。
python
# 普通函数
def add(x, y):
return x + y
# 等价的 Lambda 函数
add_lambda = lambda x, y: x + y
print(add(2, 3)) # 输出: 5
print(add_lambda(2, 3)) # 输出: 5
# 在 map() 中使用 Lambda
numbers = [1, 2, 3]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # 输出: [1, 4, 9]
3. Python 里面怎么实现 tuple 和 list 的转换
list
转tuple
: 使用tuple()
函数。tuple
转list
: 使用list()
函数。
python
# list 转 tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # 输出: (1, 2, 3)
# tuple 转 list
my_tuple = (4, 5, 6)
my_list = list(my_tuple)
print(my_list) # 输出: [4, 5, 6]
4. except
的用法和作用
except
是 Python 中异常处理的关键字,用于捕获和处理 try
块中抛出的异常。它的作用是防止程序因错误而崩溃,并允许开发者自定义错误处理逻辑。
python
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以 0!") # 输出: 不能除以 0!
# 捕获多个异常
try:
value = int("abc")
except (ValueError, TypeError):
print("输入无效!") # 输出: 输入无效!
# 使用 as 获取异常信息
try:
with open("nonexistent.txt", "r") as f:
f.read()
except FileNotFoundError as e:
print(f"错误: {e}") # 输出: 错误: [Errno 2] No such file or directory: 'nonexistent.txt'
5. match()
和 search()
的作用
match()
和 search()
是 Python re
模块中用于正则表达式匹配的函数。
re.match()
: 只从字符串的开头开始匹配,如果开头不匹配则返回None
。re.search()
: 在整个字符串中搜索第一个匹配的位置。
python
import re
text = "Python 3.9 is great"
# match() 只匹配开头
result1 = re.match(r"Python", text)
print(result1.group() if result1 else "No match") # 输出: Python
result2 = re.match(r"3.9", text)
print(result2.group() if result2 else "No match") # 输出: No match
# search() 搜索整个字符串
result3 = re.search(r"3.9", text)
print(result3.group() if result3 else "No match") # 输出: 3.9
6. 怎么在一个函数里面设置一个全局变量
使用 global
关键字可以在函数内修改全局变量。如果不使用 global
,Python 会将变量视为局部变量。
python
count = 0
def increment():
global count # 声明 count 为全局变量
count += 1
increment()
print(count) # 输出: 1
increment()
print(count) # 输出: 2
注意: 尽量避免过多使用全局变量,因为它可能导致代码难以维护。
7. 单引号、双引号、三引号的区别
- 单引号
'
和 双引号"
:
用于定义单行字符串,功能相同,可互换使用。选择哪种通常取决于字符串内容是否包含引号。
python
s1 = 'Hello "world"'
s2 = "Hello 'world'"
print(s1) # 输出: Hello "world"
print(s2) # 输出: Hello 'world'
- 三引号
'''
或"""
:
用于定义多行字符串,常用于文档字符串(docstring)或长文本。
python
s3 = """This is a
multi-line
string."""
print(s3)
# 输出:
# This is a
# multi-line
# string.
8. 函数的参数传递
Python 的参数传递是"传引用",但具体行为取决于对象是可变(如列表)还是不可变(如整数、字符串)。
- 不可变对象: 修改参数不会影响外部。
- 可变对象: 修改参数会影响外部。
python
# 不可变对象(整数)
def change_number(x):
x = 100
print(f"Inside: {x}")
num = 10
change_number(num)
print(f"Outside: {num}") # 输出: Outside: 10
# 可变对象(列表)
def change_list(lst):
lst.append(4)
print(f"Inside: {lst}")
my_list = [1, 2, 3]
change_list(my_list)
print(f"Outside: {my_list}") # 输出: Outside: [1, 2, 3, 4]
9. 类变量和实例变量
- 类变量: 属于类本身,所有实例共享。
- 实例变量: 属于类的每个实例,独立存储。
python
class Dog:
species = "Canine" # 类变量
def __init__(self, name):
self.name = name # 实例变量
dog1 = Dog("Buddy")
dog2 = Dog("Max")
print(dog1.name, dog1.species) # 输出: Buddy Canine
print(dog2.name, dog2.species) # 输出: Max Canine
# 修改类变量
Dog.species = "Canis"
print(dog1.species) # 输出: Canis
print(dog2.species) # 输出: Canis
# 修改实例变量
dog1.name = "Charlie"
print(dog1.name) # 输出: Charlie
print(dog2.name) # 输出: Max