1.9 KiB
1.9 KiB
第5章 面向对象编程(OOP)
5.1 面向对象概述
- 类(Class):抽象模板,定义属性和方法
- 对象(Object):类的实例
- 封装:隐藏内部实现细节
- 继承:子类继承父类的属性和方法
- 多态:同一接口,不同实现
5.2 类和对象
class Dog:
species = "犬科"
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} 汪汪叫!"
def __str__(self):
return f"{self.name}({self.age}岁)"
my_dog = Dog("旺财", 3)
print(my_dog.bark())
print(my_dog)
5.3 封装
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
5.4 继承
class Animal:
def __init__(self, name):
self.name = name
class Cat(Animal):
def speak(self):
return f"{self.name} 喵喵叫"
class Dog(Animal):
def speak(self):
return f"{self.name} 汪汪叫"
5.5 魔术方法
class Book:
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
def __str__(self):
return f"《{self.title}》 - {self.author}"
def __repr__(self):
return f"Book('{self.title}', '{self.author}', {self.price})"
def __eq__(self, other):
if isinstance(other, Book):
return self.title == other.title
return False
本章练习
- 设计一个
Student类,包含姓名、年龄、成绩属性 - 使用继承创建
Animal类及其子类 - 实现一个单例模式的配置管理器类