day22, class encapsulation

Today's Content

  • encapsulation

  • Interface

I. Packaging
1. What is encapsulation

Encapsulation is the process of hiding complex, ugly and private details inside and providing a simple interface to the outside world.

2. Why to encapsulate for the society

Encapsulation has two purposes: one is to ensure the security of key data, the other is to hide the implementation details and isolate the complexity.

3. When should it be encapsulated

Encapsulation can be used when some data do not want to be modified directly by the outside world or some functions do not want to be used by the outside world.

4. Use of Packaging

Double underscore the name of the property or function that needs to be encapsulated, as follows:

class Person(object):
    def __init__(self,id,name,age):
        self.__id = id
        self.name = name
        self.age = age
    def __address(self):
        print("The address is...".self.name)
        

The encapsulated attributes or methods can not be directly acquired or modified, but can be acquired or modified indirectly.

class Downloader:
    def __init__(self,filename,url,buffer_size):
        self.filename = filename
        self.url = url
        self.__buffer_size= buffer_size

    def start_download(self):
        if self.__buffer_size <= 1024*1024:
            print("Start downloading....")
            print("Current buffer size",self.__buffer_size)
        else:
            print("Memory exploded! ")


    def set_buffer_size(self,size):
        #Additional logic can be added to the method
        if not type(size) == int:
            print("Big Brother Buffer Size Must Be Integral")
        else:
            print("Successful buffer size modification!")
            self.__buffer_size = size

    def get_buffer_size(self):
        return self.__buffer_size

The encapsulated attribute buffer_size attribute in the code above is not directly acquired and modified by the outside world, but it is placed in a callable set_buffrt_size method. The purpose of modifying buffer_size is achieved by passing parameters to the modified method, and the purpose of obtaining buffer_size is achieved by the method get_buffer_size.

5. property Decorator

When calling method, parentheses are needed. When calling attributes, parentheses are not needed. It is easy to use errors without knowing whether method or attribute is used. It is inconvenient to invoke. In order to make the two forms of invocation consistent, the requirement can be realized by calling property decorator.

When the method invoked does not need to pass parameters:

class Downloader:
    def __init__(self,filename,url,buffer_size):
        self.filename = filename
        self.url = url
        self.__buffer_size= buffer_size
    
    @proprety
    def start_download(self):
        if self.__buffer_size <= 1024*1024:
            print("Start downloading....")
            print("Current buffer size",self.__buffer_size)
        else:
            print("Memory exploded! ")


    def set_buffer_size(self,size):
        #Additional logic can be added to the method
        if not type(size) == int:
            print("Big Brother Buffer Size Must Be Integral")
        else:
            print("Successful buffer size modification!")
            self.__buffer_size = size
    @proprety
    def get_buffer_size(self):
        return self.__buffer_size

When a parameter is required in the called method:

class Downloader:
    def __init__(self,filename,url,buffer_size):
        self.filename = filename
        self.url = url
        self.__buffer_size= buffer_size
    
    @proprety
    def start_download(self):
        if self.__buffer_size <= 1024*1024:
            print("Start downloading....")
            print("Current buffer size",self.__buffer_size)
        else:
            print("Memory exploded! ")
    
    @proprety
    def set_buffer_size(self):
        return self.__buffer_size
    
    @set_buffer_size.setter
    def set_buffer_size(self,size):
        #Additional logic can be added to the method
        if not type(size) == int:
            print("Big Brother Buffer Size Must Be Integral")
        else:
            print("Successful buffer size modification!")
            self.__buffer_size = size
            
    @proprety
    def get_buffer_size(self):
        return self.__buffer_size

6. Computing attributes

The so-called computational attribute is to obtain the value of one's own attribute, and calculate the new value to assign to another attribute, another attribute is called computational attribute.

When the value of attributes is changed, the value of attributes is invariable. At this time, the process of calculating attributes is solved by defining a method and putting the calculating process into it.

class Squre(object):
    def __init__(self,line):
        self.line = line
        self.s = self.line**2
s = Squre(3)
print(s.s)  # 9
s.line = 4
print(s.s)  # 9


# Solution
class Squre(object):
    def __init__(self,line):
        self.line = line
    
    @proprety
    def s(self):
        return self.line**2
    
s = Squre(3)
print(s.s)  # 9
s.line = 4
print(s.s)  # 16

II. Interface

1. What is an interface?

Interface is a set of functions, but the interface only contains the name of the function, not the specific implementation code. Interface is essentially a set of protocol standards, and objects that follow this standard can be invoked.

class USB:
    def open(self):
        pass

    def close(self):
        pass

    def  read(self):
        pass

    def write(self):
        pass

class Mouse(USB):
    def open(self):
        print("Mouse boot.....")

    def close(self):
        print("The mouse shut down...")

    def read(self):
        print("The cursor position is obtained.....")

    def write(self):
        print("Writing is not supported by mouse....")


def pc(usb_device):
    usb_device.open()
    usb_device.read()
    usb_device.write()
    usb_device.close()

m = Mouse()
# Pass the mouse to the computer
pc(m)

class KeyBoard(USB):
    def open(self):
        print("Keyboard-Power-on.....")

    def close(self):
        print("The keyboard is off...")

    def read(self):
        print("Get the key character....")

    def write(self):
        print("Can be written to light color....")

# Here comes a keyboard object
k = KeyBoard()
pc(k)

In the above case, once the PC code is completed, no matter what kind of device in the later period, as long as the USB interface protocol is followed, it can be called by the computer. Interface is mainly to facilitate the user of the object, reduce the difficulty of learning users, as long as learning a set of methods of use, you can be invariable and changeable.

2. Interface in python

In python, the pursuit of time does not limit how programmers can write code, so there is no interface. For example, the USB class in the above code can be written without writing. When writing functions of mouse and keyboard, as long as the programmer complies with the requirement to write code, in python, a programmer should consciously abide by the rules.

3. Use of abc module

Abstract classes: classes that contain abstract methods (methods without function bodies) to restrict the abstract methods that must be defined in subclasses. The USB class in the above code is an abstract class.

If a programmer does not follow the definition of abstract methods in abstract classes and defines other methods or does not define a certain method, then it can be restricted by calling abc module, and fail to follow the definition of abstract methods.

import abc

class AClass(metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def run(self):
        pass
    @abc.abstractmethod
    def run1(self):
        pass


class B(AClass):

    def run(self):
        print("runrunrurn...")

b = B()

Class B in the appeal code does not define the run1() method, and the program can not run normally.

Keywords: Go Attribute Python

Added by Craig79 on Fri, 26 Jul 2019 11:50:25 +0300