面向对象编程(OOP)是一种流行的编程范式,它将数据和操作数据的方法封装在一起形成对象。OOP的核心概念包括类(Class)、对象(Object)、封装(Encapsulation)、继承(Inheritance)和多态(Polymorphism)。下面,我将通过一些经典例题,帮助你更好地理解和掌握这些核心概念。
类与对象
例题1:定义一个Student类,包含属性name和age,以及方法study。
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def study(self):
print(f"{self.name} is studying.")
# 创建对象
student1 = Student("Alice", 20)
student1.study()
解析:在这个例子中,我们定义了一个Student类,它有两个属性:name和age。__init__方法是一个特殊的方法,用于初始化对象。study方法用于打印学生正在学习的信息。
封装
例题2:定义一个BankAccount类,包含属性balance,并且提供一个方法deposit用于存款,一个方法withdraw用于取款。确保取款时余额不能为负。
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if self.__balance >= amount:
self.__balance -= amount
else:
print("Insufficient balance.")
def get_balance(self):
return self.__balance
# 创建对象
account = BankAccount(100)
account.deposit(50)
print(account.get_balance()) # 输出: 150
account.withdraw(200) # 输出: Insufficient balance.
print(account.get_balance()) # 输出: 150
解析:在这个例子中,我们使用了双下划线__来定义一个私有属性__balance,这表示该属性只能被类内部的方法访问。deposit和withdraw方法分别用于存款和取款,get_balance方法用于获取账户余额。
继承
例题3:定义一个GraduateStudent类,继承自Student类,并添加一个属性degree。
class GraduateStudent(Student):
def __init__(self, name, age, degree):
super().__init__(name, age)
self.degree = degree
# 创建对象
grad_student = GraduateStudent("Bob", 25, "Master")
grad_student.study()
print(grad_student.degree) # 输出: Master
解析:在这个例子中,GraduateStudent类继承自Student类。我们通过调用super().__init__(name, age)来调用父类的构造函数。这样,我们就可以在GraduateStudent类中使用name和age属性。
多态
例题4:定义一个Animal类,包含方法make_sound。然后定义Dog和Cat类,继承自Animal类,并分别实现make_sound方法。
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print("Woof!")
class Cat(Animal):
def make_sound(self):
print("Meow!")
# 创建对象
dog = Dog()
cat = Cat()
dog.make_sound() # 输出: Woof!
cat.make_sound() # 输出: Meow!
解析:在这个例子中,Animal类是一个基类,它定义了一个抽象方法make_sound。Dog和Cat类继承自Animal类,并分别实现了make_sound方法。这样,我们就可以根据对象的具体类型来调用相应的方法。
通过以上经典例题,你可以更好地理解面向对象编程的核心概念。在实际编程中,这些概念可以帮助你编写更清晰、更可维护的代码。
