面向对象
class 与实例
class Person:
def __init__(self, name: str):
self.name = name
def hello(self) -> str:
return f"hi, {self.name}"
p = Person("alice")
print(p.hello())
__init__:初始化实例属性self:当前实例
继承
class Animal:
def speak(self) -> str:
return "..."
class Dog(Animal):
def speak(self) -> str:
return "woof"
print(Dog().speak())
子类可覆盖父类方法;需要复用父类逻辑时用 super()。
常用魔术方法
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self) -> str:
return f"Vector({self.x}, {self.y})"
def __add__(self, other: "Vector") -> "Vector":
return Vector(self.x + other.x, self.y + other.y)
print(Vector(1, 2) + Vector(3, 4))
常见:__repr__ / __str__ / __eq__ / __len__ / __getitem__。
要点
- 类是模板,实例是对象
- 用继承表达「is-a」;别为了 OOP 而 OOP
- 魔术方法让对象能融入 Python 语法协议