3 May 18
Review (object-oriented + socket (network) programming)
1、 Foo.x 《=》 Foo.__dict__['x']
2、 import settings
import uuid
class Mysql:
def __init__(self,host,port):
self.host=host
self.port=port
def tell_info(self):
print("<%s:%s>" %(self.host,self.port))
@classmethod
def from_conf(cls):
return cls(settings.HOST, settings.PORT)
@staticmethod
def create_id():
return uuid.uuid4()
Common usage of classmethod: use classes to provide an additional way of instantiation
Common usage of staticmethod: add a function inside the class that requires neither self nor cls
One, object-oriented review
a, functions and classes
01 Problems encountered in programming before using functions?
1. Code redundancy
2. The program organization structure is not clear
3. Poor scalability
02 Object-oriented at the code level: classes bind functions and data that can call these functions together, making the program organization structure clearer and extensible enhancement
03 The difference between defining a function and defining a class:
Defining a function only checks the syntax and does not execute the function body code
Defining a class will immediately execute the class body code, generate the class namespace, and store the names generated during the execution of the class body code in the class namespace
The purpose of storage is to take, to take out the name we defined from the namespace of the class
Foo.__dict__['host']
04 Syntax for accessing properties
Foo.property name
Foo.property name=1
del Foo.property name
Use of Class 05
Call the class to generate an object: 1. An empty object stu1 will be generated first 2. Pass stu1, along with the parameters in parentheses, to Student.__init__(stu1,'egon',18,'male')
The essence of an object is the same as that of a class. It is a container for storing names, that is, a namespace.
b. Object-oriented
01 What is an object
Objects are a combination of traits and skills
Features: Variable
Skill: Function
02 What is a class
A combination of similar characteristics and skills of a series of objects
03 The purpose of defining the class:
Is to call the class to generate the object, the object is a variable + function
c. Inheritance and derivation
01 What is inheritance?
Inherit the way to create a class, the created word class can inherit the functions or attributes of the parent class
Features: python supports multiple inheritance
Pros: Reduced code redundancy
Disadvantage: Strong coupling between subclasses and superclasses
02 A does not inherit B, but super in A will continue to look for it based on C.mro()
class A(object):
def test(self):
super().test()
class B(object):
def test(self):
print('from B')
class C(A,B):
pass
c=C()
c.test()
print(C.mro())
d. Polymorphism and polymorphism
01 Abstract class
import abc
class File(metaclass=abc.ABCMeta): #The same kind of thing: file
@abc.abstractmethod
def clickk(self):
pass
02 Duck Type
class Text: #One of the forms of the file: text file
def click(self):
print('open file')
class ExeFile: #The second form of the file: executable file
def click(self):
print('execute file')
class Process:
def click(self):
pass
e. Encapsulation (clearly distinguish between inside and outside)
01 Encapsulate the data type: Control the user's addition, deletion, modification and inspection of the modified data through the interface call
02 Encapsulate function types: isolation complexity
class ATM:
def __card(self):
print('Insert card')
def __auth(self):
print('User authentication')
def __input(self):
print('Enter the withdrawal amount')
def __print_bill(self):
print('print bill')
def __take_money(self):
print('Withdrawal')
def withdraw(self):
self.__card()
self.__auth()
self.__input()
self.__print_bill()
self.__take_money()
obj=ATM()
obj.withdraw()
f. Object-oriented key knowledge
01 ******
Why use object oriented
When to use object orientation
How to Use Object Orientation: Classes and Objects
Use of Class 02 (*****)
1. Define the class
2. Attributes of reference classes
3. Call the class to generate the object---"Instantiation
03 Use of objects (*****)
1. Reference object properties
2. Attribute search: object - "object's class ---" parent class. . .
3. Automatic value transfer of binding methods
04 Three major characteristics of object-oriented (*****):
1. Inheritance
1. Inheritance and composition (*****)
2. Abstract class (**)
3. New-style classes and classic classes and spiritual inheritance issues (*****)
4. Reuse the functions of the parent class in the subclass (*****)
2. Polymorphism: refers to the fact that an object can be used directly without considering the specific type of the object
The duck type that python advocates (*****)
3. Package
1. Automatic inflection of __ syntax:
important point:(*****)
2. The purpose of packaging: clearly distinguish the inside and the outside, the inside can be used, and the outside cannot be used directly (*****)
1: Encapsulate data attributes: allow external users to operate data indirectly, and attach additional logic to the interface
2: Encapsulating Function Properties: Isolating Complexity
g, the use of class interior decorators
01 property
class People:
def __init__(self,name,weight,height):
self.__name=name
self.wt=weight
self.ht=height
@property
def bmi(self):
return self.wt / (self.ht ** 2)
@property
def name(self):
return self.__name
@name.setter
def name(self,obj): #obj='EGON'
if not isinstance(obj,str):
raise TypeError('The value of the name must be of type str')
self.__name=obj #self.__name='EGON'
@name.deleter
def name(self):
del self.__name
p=People('egon',75,1.80)
print(p.bmi)
print(p.name)
p.name='EGON'
p.name=123
print(p.name)
from p.name
02 classmethod
03 staticmethod
Second, socket (network) programming
a. Overview of knowledge points
1. C/SB/S architecture (*****)
c:customer
s:server
b:browser
Learning objectives: open a client software and a server software, both based on network communication
2. What is a network? (*****)
1. Physical connection medium
2. Internet Protocol (English in the computer world)
3. OSI seven-layer protocol (**)
C/S
B/S
Should (should, table, meeting): application software custom protocol, HTTP, FTP, HTTP+SSL
Transport layer: TCP, UDP port based
Network layer: IP is based on IP address
Data link layer: Ethernet based on mac address
physical layer
4. How to identify a socket program that is unique in the world (*****)
ip+port
5. What is socket (*****)
Socket is an abstract interface layer between the application layer and the transport layer
Socket encapsulates protocols below tcp, we only need to follow the socket specification when writing programs for network communication
The written program naturally follows the tcp or udp protocol
6. TCP and UDP protocols (*****)
Three-way handshake to establish connection
Four waved hands to disconnect
tcp:
advantage:
Sending a piece of data must receive the confirmation of the other party before clearing the message from its own operating system cache, otherwise it will be resent.
reliable protocol
shortcoming:
The efficiency of sending data must be low udp
udp:
advantage:
High efficiency in sending data
shortcoming:
Sending a piece of data does not need to receive a confirmation message from the other party, it will immediately clear the message from its own operating system cache
Unreliable
b. Server:
import socket
server = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
# print(server)
# Both the server and the client need to have ip and port, but only the server binds ip and port
server.bind(('127.0.0.1',8080))
server.listen(5) # Semi-connection pool: the number of requests is limited, not the number of connections
while True:
conn,client_addr=server.accept() # Wait for the client to send a connection request
print(conn)
while True:
try:
data=conn.recv(1024) #1024 Maximum limit for receiving data
if not data:break #For linux system
conn.send(data.upper()) # Note: Sending and receiving are in bytes
except ConnectionResetError:
break
conn.close()
server.close()
Client:
import socket
client = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1',8080))
while True:
msg=input('>>: ').strip()
client.send(msg.encode('utf-8'))
data=client.recv(1024)
print(data.decode('utf-8'))
client.close()