python笔记之面向对象篇(六)
面向对象编程详解
面向对象编程(OOP)是一种编程范式,它使用"对象"来设计应用程序和计算机程序。
类和对象
类(Class)
类是创建对象的蓝图或模板,它定义了对象的属性和方法。
class Dog:# 类属性species = "Canis familiaris"# 初始化方法(构造函数)def __init__(self, name, age):# 实例属性self.name = nameself.age = age# 实例方法def bark(self):return f"{self.name} says woof!"def get_info(self):return f"{self.name} is {self.age} years old"
对象(Object)
对象是类的实例,具有类定义的属性和方法。
# 创建对象
my_dog = Dog("Buddy", 5)
your_dog = Dog("Lucy", 3)# 访问属性和方法
print(my_dog.name) # 输出: Buddy
print(my_dog.bark()) # 输出: Buddy says woof!
print(your_dog.get_info()) # 输出: Lucy is 3 years old
print(f"Both dogs are {my_dog.species}") # 访问类属性
面向对象的四大特性
1. 封装(Encapsulation)
将数据和行为包装在类中,并控制对内部数据的访问。
class BankAccount:def __init__(self, account_holder, balance=0):self.account_holder = account_holderself.__balance = balance # 私有属性# 公有方法访问私有属性def deposit(self, amount):if amount > 0:self.__balance += amountreturn f"Deposited ${amount}. New balance: ${self.__balance}"return "Invalid deposit amount"def withdraw(self, amount):if 0 < amount <= self.__balance:self.__balance -= amountreturn f"Withdrew ${amount}. New balance: ${self.__balance}"return "Invalid withdrawal amount"def get_balance(self):return self.__balance# 使用封装
account = BankAccount("Alice", 1000)
print(account.deposit(500)) # 可以操作余额
print(account.withdraw(200)) # 可以操作余额
# print(account.__balance) # 错误:无法直接访问私有属性
print(account.get_balance()) # 正确:通过公有方法访问
2. 继承(Inheritance)
允许一个类(子类)继承另一个类(父类)的属性和方法。
# 父类
class Animal:def __init__(self, name):self.name = namedef speak(self):raise NotImplementedError("Subclass must implement this method")# 子类
class Cat(Animal):def speak(self):return f"{self.name} says meow!"class Dog(Animal):def speak(self):return f"{self.name} says woof!"def fetch(self):return f"{self.name} is fetching the ball!"# 使用继承
animals = [Cat("Whiskers"), Dog("Rex")]
for animal in animals:print(animal.speak())rex = Dog("Rex")
print(rex.fetch())
3. 多态(Polymorphism)
不同类的对象对同一消息做出不同的响应。
# 多态示例
def animal_sound(animal):print(animal.speak