面向对象编程(Object-Oriented Programming,简称 OOP)是 Python 编程语言的核心特性之一。它允许我们创建对象,这些对象是类的实例。下面是一些关于 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())
继承
继承是 OOP 中的另一个重要概念,它允许一个类继承另一个类的属性和方法。
class Puppy(Dog):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
puppy = Puppy("Max", 2, "Brown")
print(puppy.bark())
print(puppy.color)
封装
封装是隐藏对象的内部状态和实现细节,并仅通过公共接口与外部交互。
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 funds")
def get_balance(self):
return self._balance
account = BankAccount(100)
account.deposit(50)
print(account.get_balance()) # 输出 150
多态
多态是指允许不同类的对象对同一消息做出响应。在 Python 中,多态通常通过继承和重写方法来实现。
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 面向对象编程的内容,可以访问Python 面向对象编程教程。
图片展示
下面是一只可爱的狗的图片: