数据结构
Python有四种主要的内置数据结构:列表(List)、元组(Tuple)、集合(Set)和字典(Dictionary)。以下是它们的定义和基本操作示例:
列表
特点是:有序、可变
myList = [1,2,3]
myList.append(4)
print(myList)
元组
特点:有序、不可变
my_tuple = (1, 2, 3)
# my_tuple[0] = 4 # 这会报错,因为元组不可变
print(my_tuple) # 输出: (1, 2, 3)
集合
特点:无序、元素唯一
my_set = {1,2,3}
my_set.add(4)
print(my_set)
字典
特点是:键值对
my_dict = {'a': 1, 'b': 2}
my_dict['c'] = 3
print(my_dict)
面向对象编程
OOP包括:类、继承和多态
类
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} 说 汪!"
dog = Dog("大黄")
print(dog.bark()) # 输出: 大黄 说 汪!
继承
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} 说 汪!"
class Puppy(Dog):
def bark(self):
return f"{self.name} 说 嗷呜!"
puppy = Puppy("小白")
print(puppy.bark()) # 输出: 小白 说 嗷呜!
多态
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} 说 汪!"
class Puppy(Dog):
def bark(self):
return f"{self.name} 说 嗷呜!"
def make_sound(animal):
return animal.bark()
dog = Dog("大黄")
puppy = Puppy("小白")
print(make_sound(dog)) # 输出: 大黄 说 汪!
print(make_sound(puppy)) # 输出: 小白 说 嗷呜!
异常处理
try:
x = 1 / 0
except ZeroDivisionError:
print("不能除以零!")
finally:
print("无论如何都会执行。")
装饰器
装饰器用于修改函数或类的行为,常用于日志、权限控制等。
def log_decorator(func):
def wrapper(*args, **kwargs):
print(f"调用 {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_decorator
def add(a, b):
return a + b
print(add(2, 3))
生成器
生成器用于创建可迭代对象,适合处理大数据集,节省内存。
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
for num in count_up_to(500000000000000000000):
print(num)
上下文管理器
上下文管理器用于资源管理,常with
语句配合使用。
文件操作示例
with open('file.txt', 'r') as f:
content = f.read()
自定义上下文管理器
class MyContext:
def __enter__(self):
print("进入上下文")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("退出上下文")
with MyContext() as mc:
print("在上下文中")
常用 Python 装饰器
@property
将方法转换为属性,允许像访问字段一样调用方法,支持 getter 和 setter。
class Circle:
def __init__(self, radius,ccos):
self._radius = radius
self._ccos = ccos
@property
def radius(self):
return self._radius
@property
def ccos(self):
return self._ccos
@radius.setter
def radius(self, value):
if value > 0:
self._radius = value
else:
raise ValueError("Radius must be positive")
@ccos.setter
def ccos(self, value):
if value > 10:
self._ccos = value
else:
raise ValueError("Ccos must be positive")
circle = Circle(5,7)
print(circle.radius) # 输出: 5
circle.radius = 10
circle.ccos = 3
print(circle.radius) # 输出: 10
print(circle.ccos) # 输出: 10
@classmethod
定义类方法,第一个参数为类本身(通常命名为 cls),适合工厂方法或类级操作。
class Circle:
pi = 3.14159
def __init__(self, radius):
self.radius = radius
@classmethod
def create_circle(cls, radius):
return cls(radius)
circle = Circle.create_circle(5)
print(circle.pi) # 输出: 3.14159
print(circle.radius) # 输出: 5
@staticmethod
定义静态方法,不接受 self 或 cls 参数,适合与类相关但不依赖实例或类的工具函数。
class Math:
@staticmethod
def add(a, b):
return a + b
print(Math.add(2, 3)) # 输出: 5
@functools.wraps
在自定义装饰器中用于保留原始函数的元数据(如__name__ 和 __doc__),确保调试和文档信息正确。
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("Before calling", func.__name__)
result = func(*args, **kwargs)
print("After calling", func.__name__)
return result
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# 输出:
# Before calling say_hello
# Hello!
# After calling say_hello
@functools.lru_cache
缓存函数的结果,避免重复计算,适用于计算密集型函数,提升性能。
import functools
@functools.lru_cache(maxsize=2)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(50))
@contextlib.contextmanager
将生成器函数转换为上下文管理器,可用于 with 语句,简化资源管理。
from contextlib import contextmanager
@contextmanager
def my_context():
print("Entering context")
try:
yield
finally:
print("Exiting context")
with my_context():
print("Inside context")
# 输出:
# Entering context
# Inside context
# Exiting context
@atexit.register
注册一个函数,在程序退出时调用,适合清理任务。
import atexit
@atexit.register
def goodbye():
print("Goodbye!")
print("Hello!")
# 输出:
# Hello!
# Goodbye! (当程序退出时)