在掌握了 Python 基础语法之后,面向对象编程(OOP)是你必须掌握的重要技能。本文将带你从零开始学习 Python 的面向对象编程。
一、什么是面向对象编程
面向对象编程(Object-Oriented Programming,OOP)是一种编程范式,它将数据和操作数据的方法组织在一起,形成"对象"。
核心概念:
- 类(Class):对象的蓝图或模板
- 对象(Object):类的实例
- 属性(Attribute):对象的数据
- 方法(Method):对象的行为
二、定义类和创建对象
1. 基本语法- class Dog:
- """这是一个狗的类"""
-
- # 类属性
- species = "Canis familiaris"
-
- def __init__(self, name, age):
- """构造方法,创建对象时自动调用"""
- self.name = name # 实例属性
- self.age = age
-
- def description(self):
- """描述方法"""
- return f"{self.name} 今年 {self.age} 岁"
-
- def speak(self, sound):
- """说话方法"""
- return f"{self.name} 说: {sound}"
- # 创建对象
- my_dog = Dog("Buddy", 3)
- print(my_dog.description())
- print(my_dog.speak("汪汪汪"))
复制代码 2. self 关键字
self 代表类的实例本身,必须在方法定义中作为第一个参数。
三、三大特性
1. 封装(Encapsulation)
将数据和方法包装在一起,隐藏内部实现细节。- class BankAccount:
- def __init__(self, owner, balance=0):
- self.owner = owner
- self.__balance = balance
-
- def deposit(self, amount):
- if amount > 0:
- self.__balance += amount
- return f"存入 {amount} 元"
- return "存款金额必须大于0"
-
- def withdraw(self, amount):
- if amount > self.__balance:
- return "余额不足"
- self.__balance -= amount
- return f"取出 {amount} 元"
复制代码 2. 继承(Inheritance)
子类继承父类的属性和方法。- class Animal:
- def __init__(self, name, age):
- self.name = name
- self.age = age
-
- def speak(self):
- raise NotImplementedError("子类必须实现此方法")
- class Cat(Animal):
- def speak(self):
- return f"{self.name} 说: 喵喵喵"
- class Dog(Animal):
- def speak(self):
- return f"{self.name} 说: 汪汪汪"
复制代码 3. 多态(Polymorphism)- def animal_speak(animal):
- print(animal.speak())
- animals = [Cat("咪咪", 2), Dog("旺财", 3)]
- for animal in animals:
- animal_speak(animal)
复制代码 四、特殊方法(魔术方法)
- class Book:
- def __init__(self, title, author, pages):
- self.title = title
- self.author = author
- self.pages = pages
-
- def __str__(self):
- return f"《{self.title}》作者: {self.author}"
-
- def __len__(self):
- return self.pages
复制代码 五、类方法与静态方法
- class MathUtils:
- @staticmethod
- def add(x, y):
- return x + y
-
- @classmethod
- def create_random(cls):
- import random
- return cls(random.randint(1, 100))
复制代码 六、学习建议
- 理解概念:类、对象、封装、继承、多态是 OOP 的核心
- 多练习:从简单案例开始
- 看源码:阅读优秀的开源项目
- 设计模式:掌握常用的设计模式
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |