Python 封装的奥秘

PythonBeginner
立即练习

介绍

In an era where the mystique of the ancient world still thrives, there lies a hidden temple shrouded in mystery and guarded by the spectral sentinel, a ghostly guardian. This temple is said to hold the secret of encapsulation, a mystical power that protects the temple's treasures much like how encapsulation in Python protects the integrity of an object's data. As an aspiring Python mage, your goal is to uncover these secrets, navigate through the guardian's puzzles, and master the art of encapsulation in Python to claim the arcane knowledge within.

创建 Sentinel 类

In this step, you will begin your journey by crafting a class representing the ghostly guardian, which will be your first encounter with encapsulation in Python. This guardian stores a secret message that can only be accessed through a specific method, demonstrating the power of private attributes. You'll be creating the Sentinel class with private attributes and methods to protect its secrets.

Now, open ~/project/sentinel.py in your preferred text editor and add the following code:

class Sentinel:
    def __init__(self):
        self.__message = 'The key to encapsulation lies within the walls.'

    def reveal_message(self):
        return self.__message

guardian = Sentinel()
print(guardian.reveal_message())

In this code, __message is a private attribute, denoted by the double underscores, which means it is only accessible within the class itself. The reveal_message method provides controlled access to the __message attribute.

Try running the code:

python sentinel.py

You should see the guardian's secret message printed:

The key to encapsulation lies within the walls.

增强守护者

在这一步中,你将通过为 Sentinel 类添加一个方法来增强其功能,该方法允许在提供正确口令的情况下修改秘密信息。这将进一步确保 Sentinel 的封装性,并展示如何在 Python 类中封装数据和行为。

使用以下代码更新 sentinel.py

## sentinel.py

class Sentinel:
    def __init__(self):
        self.__message = 'The key to encapsulation lies within the walls.'
        self.__passphrase = 'abracadabra'

    def reveal_message(self):
        return self.__message

    def change_message(self, new_message, passphrase):
        if passphrase == self.__passphrase:
            self.__message = new_message
        else:
            print('Incorrect passphrase!')

guardian = Sentinel()
guardian.change_message('Encapsulation is powerful!', 'abracadabra')
print(guardian.reveal_message())

现在,当你运行代码时:

python sentinel.py

如果使用了正确的口令,你将看到信息已被更新:

Encapsulation is powerful!

总结

在本实验中,你进入了一个古老原则与现代 Python 封装概念相映成趣的世界。你创建了一个 Sentinel 类,它使用私有属性来守护其秘密,学习了如何通过公共方法操作这些属性,并通过口令强制执行访问控制。本实验的设计旨在通过实践的方式帮助你理解 Python 类的私有和公共接口,强化了封装不仅是隐藏细节,更是暴露正确细节的理念。

通过这个练习,你对为什么封装是面向对象编程的基本要素以及如何在 Python 中优雅地实现封装有了更深入的理解。请记住,编写优秀代码的艺术往往在于创建一个揭示必要内容同时保护核心逻辑的外壳,就像我们古老传说中的神秘守护者一样。