林湘 發表於 2026-3-22 08:49:00

Python 面向对象编程:从入门到实践

<p>在掌握了 Python 基础语法之后,面向对象编程(OOP)是你必须掌握的重要技能。本文将带你从零开始学习 Python 的面向对象编程。</p>
<h3>一、什么是面向对象编程</h3>
<p>面向对象编程(Object-Oriented Programming,OOP)是一种编程范式,它将数据和操作数据的方法组织在一起,形成"对象"。</p>
<p><strong>核心概念:</strong></p>
<ul>
<li>类(Class):对象的蓝图或模板</li>
<li>对象(Object):类的实例</li>
<li>属性(Attribute):对象的数据</li>
<li>方法(Method):对象的行为</li>
</ul>
<h3>二、定义类和创建对象</h3>
<p><strong>1. 基本语法</strong></p>
<pre class="brush:python">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("汪汪汪"))</pre>
<p><strong>2. self 关键字</strong></p>
<p>self 代表类的实例本身,必须在方法定义中作为第一个参数。</p>
<h3>三、三大特性</h3>
<p><strong>1. 封装(Encapsulation)</strong></p>
<p>将数据和方法包装在一起,隐藏内部实现细节。</p>
<pre class="brush:python">class BankAccount:
    def __init__(self, owner, balance=0):
      self.owner = owner
      self.__balance = balance
   
    def deposit(self, amount):
      if amount &gt; 0:
            self.__balance += amount
            return f"存入 {amount} 元"
      return "存款金额必须大于0"
   
    def withdraw(self, amount):
      if amount &gt; self.__balance:
            return "余额不足"
      self.__balance -= amount
      return f"取出 {amount} 元"</pre>
<p><strong>2. 继承(Inheritance)</strong></p>
<p>子类继承父类的属性和方法。</p>
<pre class="brush:python">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} 说: 汪汪汪"</pre>
<p><strong>3. 多态(Polymorphism)</strong></p>
<pre class="brush:python">def animal_speak(animal):
    print(animal.speak())

animals =
for animal in animals:
    animal_speak(animal)</pre>
<h3>四、特殊方法(魔术方法)</h3>
<pre class="brush:python">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</pre>
<h3>五、类方法与静态方法</h3>
<pre class="brush:python">class MathUtils:
    @staticmethod
    def add(x, y):
      return x + y
   
    @classmethod
    def create_random(cls):
      import random
      return cls(random.randint(1, 100))</pre>
<h3>六、学习建议</h3>
<ol>
<li>理解概念:类、对象、封装、继承、多态是 OOP 的核心</li>
<li>多练习:从简单案例开始</li>
<li>看源码:阅读优秀的开源项目</li>
<li>设计模式:掌握常用的设计模式</li>
</ol><br><br>
来源:https://www.cnblogs.com/cartech/p/19750431
頁: [1]
查看完整版本: Python 面向对象编程:从入门到实践