第四单元:面向对象编程

约2周学习时间,掌握面向对象编程的核心概念和实践

4.1 面向对象编程概述

面向对象编程(OOP)是一种编程范式,它将数据和操作数据的方法组织成对象。在Python中,几乎所有东西都是对象。

面向对象编程的核心概念

类 (Class)

类是对象的蓝图或模板,定义了对象的属性和方法。

对象 (Object)

对象是类的实例,具有类定义的属性和方法。

属性 (Attribute)

属性是对象的特征或数据。

方法 (Method)

方法是对象的行为或操作。

4.2 类的定义与使用

定义类

class ClassName:     def __init__(self, parameters):         # 初始化方法         self.attribute = value          def method(self, parameters):         # 方法定义         pass

创建对象

# 定义一个Person类
class Person:     def __init__(self, name, age):         self.name = name         self.age = age          def greet(self):         print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# 创建对象
person1 = Person("Alice", 25) person2 = Person("Bob", 30)
# 访问属性
print(person1.name) # Alice print(person2.age) # 30
# 调用方法
person1.greet() # Hello, my name is Alice and I am 25 years old.

4.3 继承

继承是面向对象编程的重要特性,它允许我们创建一个新类,继承现有类的属性和方法。

# 定义父类
class Animal:     def __init__(self, name):         self.name = name          def speak(self):         print(f"{self.name} makes a sound.")
# 定义子类,继承Animal
class Dog(Animal):     def speak(self):         print(f"{self.name} barks.")
class Cat(Animal):     def speak(self):         print(f"{self.name} meows.")
# 创建对象
animal = Animal("Generic animal") dog = Dog("Rex") cat = Cat("Felix")
# 调用方法
animal.speak() # Generic animal makes a sound. dog.speak() # Rex barks. cat.speak() # Felix meows.

super() 函数

super() 函数用于调用父类的方法,通常用于初始化方法中。

class Person:     def __init__(self, name, age):         self.name = name         self.age = age
class Student(Person):     def __init__(self, name, age, student_id):         super().__init__(name, age) # 调用父类的初始化方法         self.student_id = student_id          def get_info(self):         return f"{self.name}, {self.age} years old, ID: {self.student_id}"
student = Student("Alice", 20, "S12345") print(student.get_info()) # Alice, 20 years old, ID: S12345

4.4 多态

多态是指不同类的对象可以响应相同的方法调用,但产生不同的行为。

class Shape:     def area(self):         pass
class Rectangle(Shape):     def __init__(self, width, height):         self.width = width         self.height = height          def area(self):         return self.width * self.height
class Circle(Shape):     def __init__(self, radius):         self.radius = radius          def area(self):         import math         return math.pi * self.radius ** 2
# 多态示例
shapes = [Rectangle(4, 5), Circle(3)]
for shape in shapes:     print(f"Area: {shape.area()}")
# 输出: # Area: 20 # Area: 28.274333882308138

4.5 封装

封装是指将数据和操作数据的方法捆绑在一起,对外部隐藏实现细节。在Python中,我们使用下划线来表示私有属性和方法。

class Person:     def __init__(self, name, age):         self.name = name # 公共属性         self._age = age # 受保护属性         self.__salary = 5000 # 私有属性          def get_age(self):         return self._age          def set_age(self, age):         if age > 0 and age < 150:             self._age = age         else:             print("Invalid age")
person = Person("Alice", 25)
# 访问公共属性
print(person.name) # Alice
# 访问受保护属性(不推荐直接访问)
print(person._age) # 25
# 尝试访问私有属性(会失败)
# print(person.__salary) # 错误
# 使用方法访问属性
print(person.get_age()) # 25 person.set_age(30) print(person.get_age()) # 30

单元小结

通过本单元的学习,你已经掌握了面向对象编程的核心概念,包括类的定义与使用、继承、多态和封装。面向对象编程是一种强大的编程范式,它可以帮助我们更好地组织和管理代码,提高代码的可复用性和可维护性。

Python 代码运行器

运行结果:

点击"运行代码"查看结果...