0Pricing
Python For Kids · 课时

封装

探索高级面向对象编程概念。

封装 是 CoddyKit 上的免费 Python For Kids 课时。 这是第 4 节课,共 5 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python For Kids 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python For Kids 课程共包含 5 节课。

封装

欢迎回到面向对象编程(OOP)课程!今天,我们将学习 Python 中的封装。封装是一个重要概念,有助于保护类中的数据和方法。

封装 — 插图 1

什么是封装?

封装是指将数据(attributes)以及操作这些数据的方法(函数)组合到一个称为类的单一单元中。它还会限制对对象某些组件的直接访问,也就是说,对象的内部表示会对外部隐藏。

  • 数据隐藏:保护对象的内部状态,避免受到意外干扰。
  • 访问控制:定义数据和方法的访问或修改方式。

封装可确保对象管理自己的数据,并且只公开必要的内容。

访问修饰符

在 Python 中,封装通过访问修饰符实现,用于控制类成员(attributes 和方法)的可见性。访问修饰符有三种类型:

  • 公共:可以从任何位置访问。
  • 受保护:可以在类及其子类中访问。
  • 私有:只能在类自身内部访问。

让我们看看如何在 Python 中使用这些访问修饰符。

公共 attribute 和方法

公共成员可以从类的外部访问。默认情况下,所有 attribute 和方法都是公共的,除非另有指定。

示例:

# Defines the Person class with public attributes and methods
class Person:
    def __init__(self, name, age):
        self.name = name  # Public attribute
        self.age = age    # Public attribute

    def greet(self):
        print("Hello, my name is " + self.name + "!")  # Public method

# Creates an object of the Person class
person1 = Person("Alice", 30)

# Accesses public attributes and methods
print(person1.name)  # Output: Alice
person1.greet()      # Output: Hello, my name is Alice!

受保护的 attribute 和方法

受保护成员以前置单个下划线 (_) 表示。它们可以在类及其子类中访问,但不应从类的外部直接访问。

示例:

# Defines the Employee class with protected attributes and methods
class Employee:
    def __init__(self, name, salary):
        self._name = name      # Protected attribute
        self._salary = salary  # Protected attribute

    def _increase_salary(self, amount):
        self._salary += amount  # Protected method
        print(self._name + "'s new salary is " + str(self._salary))

# Creates an object of the Employee class
employee1 = Employee("Bob", 50000)

# Accesses protected attributes and methods (not recommended)
print(employee1._name)  # Output: Bob
employee1._increase_salary(5000)  # Output: Bob's new salary is 55000

私有 attribute 和方法

私有成员以前置双下划线 (__) 表示。它们只能在类自身内部访问,不能从类的外部直接访问。

示例:

# Defines the BankAccount class with private attributes and methods
class BankAccount:
    def __init__(self, owner, balance):
        self.__owner = owner    # Private attribute
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        self.__balance += amount  # Modifies private attribute
        print("Deposited:", amount)
        self.__show_balance()

    def __show_balance(self):
        print("Current Balance:", self.__balance)  # Private method

# Creates an object of the BankAccount class
account1 = BankAccount("Charlie", 1000)

# Attempts to access private attributes and methods (will cause errors)
# print(account1.__owner)        # AttributeError
# account1.__show_balance()      # AttributeError

# Uses public methods to interact with private attributes
account1.deposit(500)  # Output:
                        # Deposited: 500
                        # Current Balance: 1500

为什么要使用封装?

封装具有以下几项优点:

  • 控制:控制数据的访问或修改方式。
  • 安全性:保护对象的内部状态,避免发生意外更改。
  • 可维护性:使代码更易于维护,并减少错误。

封装有助于构建稳健且安全的应用程序。

封装示例:Car 类

让我们创建一个使用封装来保护其属性和方法的 Car 类。

代码:

# Defines the Car class with encapsulated attributes and methods
class Car:
    def __init__(self, make, model, year):
        self.make = make          # Public attribute
        self.model = model        # Public attribute
        self.__year = year        # Private attribute

    def get_year(self):
        return self.__year  # Public method to access private attribute

    def set_year(self, year):
        if year > 0:
            self.__year = year  # Public method to modify private attribute
            print("Year updated to", self.__year)
        else:
            print("Invalid year!")

    def __display_info(self):
        print(self.make, self.model, self.__year)  # Private method

    def show_info(self):
        self.__display_info()  # Public method that calls a private method

# Creates an object of the Car class
car1 = Car("Tesla", "Model S", 2020)

# Accesses public attributes and methods
print(car1.make)        # Output: Tesla
print(car1.get_year())  # Output: 2020

# Modifies the private attribute using a public method
car1.set_year(2021)     # Output: Year updated to 2021

# Calls a public method that interacts with a private method
car1.show_info()        # Output: Tesla Model S 2021

# Attempts to access private attributes and methods directly (will cause errors)
# print(car1.__year)         # AttributeError
# car1.__display_info()      # AttributeError
# Defines the Student class with encapsulated attributes
class Student:
    def __init__(self, name, grade):
        self.name = name      # Public attribute
        self.__grade = grade  # Private attribute

    def get_grade(self):
        return self.__grade  # Public method to access private attribute

    def set_grade(self, grade):
        if 0 <= grade <= 100:
            self.__grade = grade  # Updates the grade
        else:
            print("Invalid grade!")

# Creates an object of the Student class
student1 = Student("Diana", 85)

# Accesses and modifies the grade using public methods
print(student1.get_grade())  # Output: 85
student1.set_grade(90)
print(student1.get_grade())  # Output: 90

# Attempts to access the private attribute directly (will cause an error)
# print(student1.__grade)     # AttributeError

做得很好!

您已经学会了如何在 Python 中使用封装来保护类中的数据和方法。封装可以帮助您控制对对象数据的访问,使程序更加安全且易于维护。请继续练习,为类设计适当的访问修饰符,以提升您的编程技能!

封装 — 插图 10

常见问题解答

「封装」课时是免费的吗?

是的 — 「封装」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python For Kids 课程的其余内容,请升级到 CoddyKit PRO。 Python For Kids 课程共包含 5 节课。

「封装」这节课中我会学到什么?

探索高级面向对象编程概念。 你通过在浏览器中直接运行的动手代码来练习 Python For Kids,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Python For Kids 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Python For Kids 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 5 节。

「封装」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Python For Kids 课中编写并运行代码吗?

能。每节 Python For Kids 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 面向对象编程简介
  2. 创建类与对象
  3. 继承
  4. 封装
  5. 多态
← 返回 Python For Kids