面向对象编程(OOP)是Python的核心编程范式,据2023年Stack Overflow调查显示,Python开发者中92%在日常工作中使用类。类能有效组织代码、提高复用性,是构建复杂程序的基石。
类提供:
类如同"智能模具":
Python 3.6+,无额外依赖
class Dog:
# 类属性(所有实例共享)
species = "Canis familiaris"
# 构造方法(初始化实例)
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
# 实例方法
def description(self):
return f"{self.name} is {self.age} years old"
# 另一个实例方法
def speak(self, sound):
return f"{self.name} says {sound}"
# 创建实例
buddy = Dog("Buddy", 3)
print(buddy.description()) # Buddy is 3 years old
print(buddy.speak("Woof")) # Buddy says Woof
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
raise NotImplementedError("子类必须实现此方法")
class Cat(Animal): # 继承Animal
def make_sound(self): # 方法重写
return "Meow~"
class Duck(Animal):
def make_sound(self):
return "Quack!"
# 多态演示
animals = [Cat("Kitty"), Duck("Donald")]
for animal in animals:
print(f"{animal.name}: {animal.make_sound()}")
# 输出:
# Kitty: Meow~
# Donald: Quack!
class Pizza:
def __init__(self, ingredients):
self.ingredients = ingredients
@classmethod # 类方法
def margherita(cls):
return cls(["mozzarella", "tomatoes"])
@staticmethod # 静态方法
def cooking_time():
return "15-20分钟"
# 使用类方法创建实例
p1 = Pizza.margherita()
print(p1.ingredients) # ['mozzarella', 'tomatoes']
# 调用静态方法
print(Pizza.cooking_time()) # 15-20分钟
案例1输出:
Buddy is 3 years old
Buddy says Woof
案例2输出:
Kitty: Meow~
Donald: Quack!
案例3输出:
['mozzarella', 'tomatoes']
15-20分钟
class BankAccount:
def __init__(self, owner, balance=0):
self._owner = owner # 受保护属性
self.__balance = balance # 私有属性
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self): # 公共访问方法
return self.__balance
account = BankAccount("Alice")
account.deposit(100)
print(account.get_balance()) # 100
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("温度不能低于绝对零度")
self._celsius = value
temp = Temperature(25)
temp.celsius = 30 # 自动调用setter方法
class Flyable:
def fly(self):
print("Flying")
class Swimmable:
def swim(self):
print("Swimming")
# 多重继承
class Duck(Flyable, Swimmable):
pass
duck = Duck()
duck.fly() # Flying
duck.swim() # Swimming
class Example:
def method(): # 错误!缺少self
print("Hello")
# 正确写法
def method(self):
print("Hello")
class Dog:
tricks = [] # 类属性
def add_trick(self, trick):
self.tricks.append(trick)
d1 = Dog()
d1.add_trick("roll over")
d2 = Dog()
print(d2.tricks) # ['roll over'] 所有实例共享!
class Parent:
def __init__(self, name):
self.name = name
class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # 必须调用父类初始化
self.age = age