面向对象编程(OOP)是 Python 中的一个核心概念。本教程将引导你了解 OOP 的基本原理和应用。
OOP 的核心概念
- 类(Class):类是创建对象的蓝图。
- 对象(Object):对象是类的实例。
- 封装(Encapsulation):将数据和操作数据的函数绑定在一起。
- 继承(Inheritance):允许一个类继承另一个类的属性和方法。
- 多态(Polymorphism):允许不同类的对象对同一消息做出响应。
实例:创建一个简单的类
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says: Woof!")
继承
class Puppy(Dog):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def play(self):
print(f"{self.name} is playing with a ball.")
多态
def make_animal_speak(animal):
animal.speak()
dog = Dog("Buddy", 5)
puppy = Puppy("Max", 1, "brown")
make_animal_speak(dog)
make_animal_speak(puppy)
图片示例
Python Dog
注意:以上代码仅为示例,具体实现可能因版本和需求而有所不同。