面向对象编程(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!"
dog = Dog("Buddy", 5)
print(dog.name) # 输出: Buddy
print(dog.bark()) # 输出: Buddy says: Woof!
继承
继承允许一个类继承另一个类的属性和方法。
class Puppy(Dog):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
puppy = Puppy("Max", 2, "black")
print(puppy.color) # 输出: black
多态
多态是指同一个操作作用于不同的对象时可以有不同的解释,产生不同的执行结果。
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
dog = Dog()
cat = Cat()
print(dog.speak()) # 输出: Woof!
print(cat.speak()) # 输出: Meow!
装饰器
装饰器是用于修改函数或类行为的函数。
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 OOP
更多关于 Python 面向对象编程的信息,请访问我们的 Python 教程。
# 注意:以上代码块仅供参考,实际运行时需要完整的 Python 环境和类定义。