面向对象编程(OOP)是 Python 中一个非常重要的概念。它可以帮助我们以更模块化和可重用的方式编写代码。下面是一些关于 Python 面向对象编程的基础教程。

类和对象

在 Python 中,类是用来创建对象的蓝图。对象是类的实例。

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        return f"{self.name} says: Woof!"

# 创建对象
my_dog = Dog("Buddy", 5)
print(my_dog.bark())

继承

继承是面向对象编程中的一个核心概念。它允许我们创建一个基于另一个类的类。

class Puppy(Dog):
    def __init__(self, name, age, color):
        super().__init__(name, age)
        self.color = color

    def play(self):
        return f"{self.name} is playing with a ball!"

# 创建子类对象
puppy = Puppy("Max", 3, "brown")
print(puppy.bark())
print(puppy.play())

多态

多态是指同一操作作用于不同的对象时可以有不同的解释。在 Python 中,多态通常通过方法重写来实现。

class Animal:
    def sound(self):
        return "Animal makes a sound"

class Dog(Animal):
    def sound(self):
        return "Dog barks"

class Cat(Animal):
    def sound(self):
        return "Cat meows"

# 多态示例
animals = [Dog(), Cat()]
for animal in animals:
    print(animal.sound())

装饰器

装饰器是 Python 中一个非常有用的功能,可以用来扩展函数或方法的行为。

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

扩展阅读

更多关于 Python 面向对象编程的内容,您可以参考我们的面向对象编程高级教程