面向对象编程(OOP)是 Python 中一个非常重要的概念。它提供了一种组织代码的方式,使得代码更加模块化和可重用。
类与对象
在 OOP 中,类是创建对象的蓝图。对象是类的实例。
- 类:定义了对象的属性和方法。
- 对象:类的具体实例。
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says: Woof!"
dog = Dog("Buddy", 5)
print(dog.bark())
继承
继承允许一个类继承另一个类的属性和方法。
class Puppy(Dog):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
puppy = Puppy("Buddy", 1, "brown")
print(puppy.bark())
print(puppy.color)
封装
封装是指将对象的属性和方法封装在一起,只暴露必要的接口。
class BankAccount:
def __init__(self, owner, balance=0):
self.__balance = balance # 私有属性
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient funds")
def get_balance(self):
return self.__balance
account = BankAccount("Alice", 100)
account.deposit(50)
print(account.get_balance())
多态
多态是指同一操作作用于不同的对象时可以有不同的解释和表现。
class Animal:
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
dog = Dog()
cat = Cat()
print(dog.sound()) # 输出: Woof!
print(cat.sound()) # 输出: Meow!
更多关于 Python OOP 的内容,请访问Python 面向对象编程教程。
Python OOP