On encapsulation of three main characteristics of python object

Posted by Sj0wKOoMel on Sun, 16 Jun 2019 00:06:34 +0200

We all have TV sets in our house, from power on, browsing programs, changing stations to power off. We don't need to know the details inside the TV. We just need to press the remote control to complete the operation when we are using it. This is the encapsulation of functions.

When using Alipay to make payment, you only need to give the two-way code to the payee or sweep the two-way code provided by the payee to complete the payment. You do not need to know the payment interface of Alipay and the ability of background processing data. This is the encapsulation of the method.

Everywhere in life is the concept of encapsulation. Encapsulation is not simply a hiding of meaning The primary reason for encapsulating data is to protect privacy The main reason for encapsulation methods is isolation complexity

In a programming language, an interface is provided to the outside world. Functions that represent this interface are often referred to as interface functions.

There are two levels of packaging:

The first level of encapsulation is the creation of namespaces for classes and objects, respectively.Names can only be accessed by adding "." or obj. to the class name

The second level of encapsulation hides certain properties and methods in a class, or defines them as private, uses them only inside the class, is not accessible outside the class, or leaves a small number of interfaces (functions) for external access

However, regardless of the level of encapsulation, the external interface to access the internal hidden content should be provided.

In python, hidden attributes (set to private attributes) are implemented using double underscores.

What can you do to hide the properties of a class in python?

Take the following example:

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

    def teach(self):
        print("%s is teaching"%self.name)

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

    def study(self):
        print("%s is studying"%self.name)

Create a teacher s1 and a student s1 with the classes defined.

t1=Teacher("alex",28,"python")
s1=Student("jack",22,"group2")

Call the name, age and other characteristics of the teacher and the student respectively:

print(t1.name,t1.age,t1.course)
print(s1.name,s1.age,s1.group)

Return the following information:

alex 28 python
jack 22 group2

Invoke the teacher's teaching skills and the student's learning skills:

t1.teach()
s1.study()

The information returned is as follows:

alex is teaching
jack is studying

After hiding some of these two types of attributes, the code is as follows:

class Teacher:
    def __init__(self,name,age,course):
        self.__name=name
        self.__age=age
        self.__course=course

    def teach(self):
        print("%s is teaching"%self.__name)

class Student:
    def __init__(self,name,age,group):
        self.__name=name
        self.__age=age
        self.__group=group

    def study(self):
        print("%s is studying"%self.__name)

Create examples of teachers and students:

t1=Teacher("alex",28,"python")
s1=Student("jack",22,"group2")

Then use the same method as before to invoke the characteristics of teachers and students:

print(t1.name,t1.age,t1.course)
print(s1.name,s1.age,s1.group)

At this point, the call will fail, and the output information is as follows:

Traceback (most recent call last):
  File "E:/py_code/oob.py", line 114, in <module>
    print(t1.name,t1.age,t1.course)
AttributeError: 'Teacher' object has no attribute 'name

Re-invoke the teacher's teaching skills and the student's learning skills:

t1.teach()
s1.study()

The information returned is as follows:

alex is teaching
jack is studying

If you can see the hidden attributes and access the attributes inside the object as before, you will get an attribute error. How can you access the internal attributes now? Now look at the namespaces for t1 and s1

print(t1.__dict__)
{'_Teacher__name': 'alex', '_Teacher__age': 28, '_Teacher__course': 'python'}
print(s1.__dict__)
{'_Student__name': 'jack', '_Student__age': 22, '_Student__group': 'group2'}

You can see that the namespaces of t1 and s1 have changed completely. Now what can you see when you visit the key in the t1 namespace?

print(t1._Teacher__name)
print(t1._Teacher__age)
print(t1._Teacher__course)

Return as follows:

alex
28
python

There was no error this time. It seems that hidden attributes can be accessed through the way of'_class name_u attribute'. To get and hide attributes, look directly at the same values as their internal attributes.

python has some features for such hiding:
1. The _X absorptive energy defined in the class is used internally, such as self._X, referring to the result of the distortion.
2. This distortion is actually an external change that cannot be accessed externally by the name _X.

In fact, python's encapsulation of this level requires a function to be defined in the class. This allows hidden attributes to be accessed inside the class and used externally, and this form of hiding does not Real restrictions access properties directly from outside, knowing that class names can invoke hidden properties of classes just like property names.

python does not really prevent developers from accessing private properties of classes, and modules follow this convention. Many modules have methods that start with a single underline, which is used here

from module import *

These methods are not imported and must be passed

from module import _private_module

To import this type of module.

Topics: Python Attribute Programming