0. Python
数据模型与魔法方法
class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"Point({self.x}, {self.y})" def __str__(self): return f"({self.x}, {self.y})" def __bool__(self): return self.x != 0 or self.y != 0 p = Point(1, 2) print(repr(p)) # Point(1, 2) print(str(p)) # (1, 2) print(bool(p)) # True
class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __iadd__(self, other): self.x += other.x self.y += other.y return self def __repr__(self): return f"Vector({self.x}, {self.y})" v1 = Vector(1, 2) v2 = Vector(3, 4) print(v1 + v2) # Vector(4, 6) v1 += v2 print(v1) # Vector(4, 6)
class MyList: def __init__(self, items): self.items = list(items) def __getitem__(self, index): return self.items[index] def __setitem__(self, index, value): self.items[index] = value def __delitem__(self, index): del self.items[index] def __len__(self): return len(self.items) def __iter__(self): return iter(self.items) l = MyList([1, 2, 3]) print(l[0]) # 1 l[1] = 20 print(list(l)) # [1, 20, 3] del l[2] print(list(l)) # [1, 20]
class A: def __getattr__(self, name): return f"{name} 属性不存在,但我拦截了它" a = A() print(a.foo) # foo 属性不存在,但我拦截了它class Demo: def __init__(self): self.existing = 42 def __getattr__(self, name): print(f"__getattr__ called for {name}") return f"{name} not found!" def __getattribute__(self, name): print(f"__getattribute__ called for {name}") return super().__getattribute__(name) d = Demo() print(d.existing) # __getattribute__ called for existing -> 42 print(d.missing) # __getattribute__ called for missing # __getattr__ called for missing -> missing not found!class Bad: def __getattribute__(self, name): # 直接访问 self.name -> 无限递归 return self.name # b = Bad() # b.any_attr # 会触发 RecursionError # 正确做法:使用 super().__getattribute__ 或 object.__getattribute__ class Good: def __init__(self): self.x = 10 def __getattribute__(self, name): print(f"Accessing {name}") return super().__getattribute__(name) g = Good() print(g.x) # Accessing x -> 10
class Adder: def __init__(self, n): self.n = n def __call__(self, x): return x + self.n add5 = Adder(5) print(add5(10)) # 15 class Managed: def __enter__(self): print("Enter") return self def __exit__(self, exc_type, exc_val, exc_tb): print("Exit") with Managed(): print("Inside") # 输出: # Enter # Inside # Exit
class Person: def __init__(self, age): self.age = age def __lt__(self, other): return self.age < other.age p1 = Person(20) p2 = Person(30) print(p1 < p2) # True
Python 的动态特性
高阶函数与函数式编程
Python Decorator
迭代器与生成器
- 特性迭代器生成器
上下文管理器(with 语句)
元类(Metaclass)
模块与包机制
多线程、多进程、协程
Python 内存管理与垃圾回收
Python 的高级数据类型
Last updated
Was this helpful?