面向对象编程(OOP)是 Python 中一个非常重要的概念。在这个教程中,我们将探讨 OOP 的基本原理,并通过一些示例来加深理解。
OOP 基本概念
类(Class)
类是 OOP 的核心概念之一。类定义了对象的属性和行为。
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says: Woof!")
对象(Object)
对象是类的实例。每个对象都有自己的属性和方法。
my_dog = Dog("Buddy", 5)
my_dog.bark() # 输出: Buddy says: Woof!
继承(Inheritance)
继承是 OOP 中的另一个重要概念。它允许一个类继承另一个类的属性和方法。
class Puppy(Dog):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
puppy = Puppy("Max", 2, "Golden Retriever")
puppy.bark() # 输出: Max says: Woof!
封装(Encapsulation)
封装是指将对象的属性和方法封装在一起,以防止外部直接访问。
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
扩展阅读
想要了解更多关于 Python OOP 的知识,可以阅读《Python 面向对象编程指南》。
Python