23.md 3.2 KB
Newer Older
W
wizardforcel 已提交
1
# 封装
W
init  
wizardforcel 已提交
2 3 4 5 6

> 原文: [https://pythonspot.com/encapsulation](https://pythonspot.com/encapsulation)

在面向对象的 python 程序中,您可以 _ 限制对方法和变量的访问 _。 这可以防止意外修改数据,这就是 _ 封装 _。 让我们从一个例子开始。

W
wizardforcel 已提交
7
## 私有方法
W
init  
wizardforcel 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

![encapsulation](img/f9a64d9604d279e122057d7ac9086909.jpg)

encapsulation. Restricted accesss to methods or variables

我们创建了一个 Car 类,它具有两种方法:drive()和 updateSoftware()。 创建汽车对象时,它将调用私有方法 __updateSoftware()。

仅在类内部不能直接在对象上调用此函数。

```py
#!/usr/bin/env python

class Car:

    def __init__(self):
        self.__updateSoftware()

    def drive(self):
        print('driving')

    def __updateSoftware(self):
        print('updating software')

redcar = Car()
redcar.drive()
#redcar.__updateSoftware()  not accesible from object.

```

该程序将输出:

```py
updating software
driving

```

封装可以防止意外访问,但不是有意访问。

私有属性和方法并未真正隐藏,而是在其名称的开头加上了 _Car”来重命名。

实际上可以使用 redcar._Car__updateSoftware()调用该方法。

W
wizardforcel 已提交
51
## 私有变量
W
init  
wizardforcel 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125

![encapsulation-example](img/5c9510eede5c19eda3992c95d2bcb565.jpg)

Class with private variables

变量可以是私有的,这在许多情况下都可以使用。 私有变量只能在类方法内更改,而不能在类外部更改。

对象可以为您的应用程序保存关键数据,并且您不希望这些数据在代码中的任何位置都可以更改。
示例:

```py
#!/usr/bin/env python

class Car:

    __maxspeed = 0
    __name = ""

    def __init__(self):
        self.__maxspeed = 200
        self.__name = "Supercar"

    def drive(self):
        print('driving. maxspeed ' + str(self.__maxspeed))

redcar = Car()
redcar.drive()
redcar.__maxspeed = 10  # will not change variable because its private
redcar.drive()

```

如果要更改私有变量的值,则使用 setter 方法。 这只是设置私有变量值的一种方法。

```py
#!/usr/bin/env python

class Car:

    __maxspeed = 0
    __name = ""

    def __init__(self):
        self.__maxspeed = 200
        self.__name = "Supercar"

    def drive(self):
        print('driving. maxspeed ' + str(self.__maxspeed))

    def setMaxSpeed(self,speed):
        self.__maxspeed = speed

redcar = Car()
redcar.drive()
redcar.setMaxSpeed(320)
redcar.drive()

```

为什么要创建它们? 因为某些私有值可能需要在创建对象后更改,而其他私有值可能根本不需要更改。

## Python 封装

To summarize, in Python there are:

Other programming languages have protected class methods too, but Python does not.

封装使您可以更好地控制代码中的耦合程度,它允许类在不影响代码其他部分的情况下更改其实现。

[下载练习](https://pythonspot.com/download-oop-exercises/)

| 类型 | 描述 |
| --- | --- |
| 公开方法 | 可从任何地方访问 |
W
wizardforcel 已提交
126
| 私有方法 | 仅在自己的课程中可访问。 以两个下划线开头 |
W
init  
wizardforcel 已提交
127
| 公共变量 | 可从任何地方访问 |
W
wizardforcel 已提交
128
| 私有变量 | 仅在自己的类或方法(如果已定义)中可访问。 以两个下划线开头 |