610's Algorithm Teaching

面向对象编程

面向对象编程概述

面向对象编程(OOP)是一种编程范式,它使用"对象"来设计软件。OOP的主要特征包括封装、继承和多态。Python是一门支持面向对象编程的语言。

类与对象

类是对象的模板,定义了对象的属性和方法。对象是类的实例化。

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

    def introduce(self):
        print(f"我叫{self.name},今年{self.age}岁。")

# 对象的创建和使用
person1 = Person("张三", 25)
person1.introduce()

person2 = Person("李四", 30)
person2.introduce()

封装

封装是将数据和操作数据的方法捆绑在一起,并隐藏内部实现细节。Python通过命名约定实现封装。

class BankAccount:
    def __init__(self, initial_balance):
        self.__balance = initial_balance # 私有属性

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

    def withdraw(self, amount):
        if amount > 0 and self.__balance >= amount:
            self.__balance -= amount
            return True
        return False

    def get_balance(self):
        return self.__balance

继承

继承允许创建新类(子类)从现有类(父类)继承属性和方法,实现代码重用。

class Animal:
    def __init__(self, name):
        self.name = name

    def eat(self):
        print(f"{self.name}吃东西")

    def make_sound(self):
        print(f"{self.name}发出声音")

# 子类
class Dog(Animal):
    def make_sound(self):
        print(f"{self.name}汪汪汪")

    def fetch(self):
        print(f"{self.name}捡球")

# 子类
class Cat(Animal):
    def make_sound(self):
        print(f"{self.name}喵喵喵")

    def climb(self):
        print(f"{self.name}爬树")

多态

多态允许不同类的对象对同一消息做出不同的响应。Python通过方法重写实现多态。

def animal_sound(animal):
    animal.make_sound()

dog = Dog("旺财")
cat = Cat("咪咪")

animal_sound(dog) # 输出:旺财汪汪汪
animal_sound(cat) # 输出:咪咪喵喵喵

特殊方法

Python提供了许多特殊方法(魔术方法),用于定义类的特殊行为。

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"Point({self.x}, {self.y})"

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3) # 输出:Point(4, 6)
print(p1 == Point(1, 2)) # 输出:True

类属性和实例属性

类属性属于类本身,所有实例共享。实例属性属于具体实例,每个实例独立。

class Circle:
    pi = 3.14159 # 类属性

    def __init__(self, radius):
        self.radius = radius # 实例属性

    def area(self):
        return Circle.pi * self.radius ** 2

print(Circle.pi) # 输出:3.14159
c1 = Circle(5)
c2 = Circle(10)
print(c1.area()) # 输出:78.53975
print(c2.area()) # 输出:314.159

类方法和静态方法

类方法使用@classmethod装饰器,静态方法使用@staticmethod装饰器。

class MathOperations:
    @classmethod
    def add(cls, a, b):
        return a + b

    @staticmethod
    def multiply(a, b):
        return a * b

print(MathOperations.add(5, 3)) # 输出:8
print(MathOperations.multiply(4, 6)) # 输出:24

学习建议

  • 理解面向对象编程的核心概念:封装、继承、多态
  • 合理使用命名约定实现封装
  • 通过继承实现代码重用和扩展
  • 使用方法重写实现运行时多态
  • 了解特殊方法的作用和使用场景
  • 区分类属性和实例属性
  • 掌握类方法和静态方法的使用
返回Python教程