This program records
1. Abstract interface
2. Static methods, class methods, property methods
3. Special methods of Class
3.1 __doc__ represents the description of the class (note)
3.2 __module__ and __class__
3.3 __init__ Constructs a method that automatically triggers execution when an object is created through a class.
3.4 __del__
3.5 __call__ object with parentheses, triggering execution
3.6 __dict__ View all members in a class or object
3.7 __str__
3.8 __getitem__, __setitem__, __delitem__
3.9 __new__ \ __metaclass__
4. Exception Handling
4.1 Basic structure
4.2 Complete structure
4.3 assertions
4.4 Custom Exceptions
5. Reflection
6. Socket programming
1. Abstract interface
Py2 notation:
Import ABC
Class Alert (object):
"' Alarm base class '"
__metaclass__ = abc. Abcmeta #必须实现子类实例化和调用send必须重写send, otherwise error
@abc. Abstractmethod
def send (self):
"Alarm Message Sending interface"
Pass
Class Mailalert (Alert):
Pass
m = Mailalert ()
M.send ()
Py3 notation:
Error if not rewritten
Class Alert (object):
"' Alarm base class '"
def send (self):
"Alarm Message Sending interface"
Raise Notimplementederror
Class Mailalert (Alert):
Pass
m = Mailalert ()
M.send ()
Error:
F:\Python\Python3\python.exe D:/python Training/our_python/day8/abstract interface. py
Traceback (most recent):
File "D:/python Training/our_python/day8/Abstract interface. py", line A, in <module>
M.send ()
File "D:/python Training/our_python/day8/Abstract interface. py", line 6, in send
Raise Notimplementederror
Notimplementederror
Correct wording:
Class Alert (object):
"' Alarm base class '"
def send (self):
"Alarm Message Sending interface"
Raise Notimplementederror
Class Mailalert (Alert):
def send (self,msg):
Print ("__send__", msg)
m = Mailalert ()
M.send ("Sssss")
Output: __send__ sssss
2. Static methods, class methods, property methods
#静态方法即不能访问公有属性也不能访问实例
#类方法只能访问公有属性, the instance cannot be accessed
#属性方法, a method is programmed with a static property that accesses the method directly, but cannot call this method
Test:
class Person (object):
Name = "Class_jack"
def __init__ (self,name):
Self.name = Name
@staticmethod #静态方法即不能访问公有属性也不能访问实例
Def eat (Name,food):
Print ("%s is eating. %s "% (Name,food))
@classmethod #类方法只能访问公有属性, cannot access instance
def walk (self):
Print ("%s is walking ..."% self.name)
@property #属性方法 a method to program a static property
Def talk (self):
Print ("%s says"% self.name)
@talk. Setter #修改属性
Def talk (Self,c_name):
Self.name = C_name
Print ("%s says"% self.name)
@talk. deleter
Def talk (self):
Print ("del%s says"% self.name)
p = person ("Jack")
P.eat ("Xiaoming", "noodle") #静态方法, passing in their own variables
P.walk () #直接访问类变量
P.talk #直接访问, but cannot be called with P.talk ()
P.talk = "TTT" #修改属性
Del P.talk #删除属性
Attribute method application--flight query
Class Flight (object):
def __init__ (self,name):
Self.flight_name = Name
def checking_status (self):
Print ("Checking flight%s status"% Self.flight_name)
Return 1
@property
def flight_status (self): # #属性方法, programming a method with a static property that only accesses
Status = Self.checking_status ()
If status = = 0:
Print ("Flight got canceled ...")
elif Status = = 1:
Print ("Flight is arrived ...")
elif Status = = 2:
Print ("Flight has departured already ...")
Else
Print ("Cannot confirm the flight status...,please check later")
@flight_status. Setter # Modifying properties
def flight_status (self, status):
Status_dic = {
0: "Canceled",
1: "Arrived",
2: "Departured"
}
Print ("\033[31;1mhas changed the flight status to \033[0m", Status_dic.get (status))
@flight_status. Deleter # Delete Property
def flight_status (self):
Print ("Status got removed ...")
f = Flight ("CA980")
F.flight_status
F.flight_status = 2 #触发 @flight_status. Setter
F.flight_status
Del f.flight_status #触发 @flight_status. deleter
F.flight_status
3. Special methods of Class
3.1 __doc__ represents the description of the class (note)
Print (f.__doc__)
3.2 __module__ and __class__
__MODULE__ represents the object of the current operation in that module
__CLASS__ represents the class of the object that is currently being manipulated
Print (f.__module__)
__main__
Print (f.__class__)
<class ' __main__. Flight ' >
3.3 __init__ Constructs a method that automatically triggers execution when an object is created through a class.
3.4 __del__
3.5 __call__ object with parentheses, triggering execution
def __call__ (self, *args, **kwargs):
Print ("__call:", Args,kwargs)
Output:
__call: (' sssss ',) {}
3.6 __dict__ View all members in a class or object
Print (f.__dict__)
Output: {' flight_name ': ' CA980 '}
3.7 __str__
If the __str__ method is defined in a class, the return value of the method is output by default when the object is printed
def __str__ (self):
Return "<flight:%s,status:%s>"% (self.flight_name,self.flight_status)
Output:
<flight:CA980,status:None>
3.8 __getitem__, __setitem__, __delitem__
def __getitem__ (self, key):
Print (' __getitem__ ', key)
def __setitem__ (self, Key, value):
Print (' __setitem__ ', key, value)
def __delitem__ (self, key):
Print (' __delitem__ ', key)
st = f[' CA980 '] #触发__getitem__
f[' CA980 '] = 1 #触发__setitem__
Del f[' CA980 '] #触发__delitem__
Output:
__getitem__ CA980
__setitem__ CA980 1
__delitem__ CA980
3.9 __new__ \ __metaclass__
Other information: https://zhuanlan.zhihu.com/p/23887627
Class Foo (object):
def __init__ (self,name):
Self.name = Name
f = Foo ("Alex")
Print type (f) # output: <class ' __main__. Foo ' > indicates that the Obj object was created by the Foo class
Print Type (foo) # Output: <type ' type ' > indicates that the Foo class object was created by the type class
Self-building a class (dynamically creating a Class):
Def talk (Self,msg):
Print ("%s is talking:%s"% (self.name,msg))
def __init__ (self,name):
Self.name = Name
Dog = Type ("Dog", (object,), {"Talk": Talk, "__init__": __init__})
Print (DOG)
Print (Type (DOG))
D = Dog ("Xiaoming")
Print (type (d))
D.talk ("Wwwwww")
Output:
<class ' __main__. Dog ' >
<class ' type ' >
<class ' __main__. Dog ' >
Xiaoming is talking:wwwwww
4. Exception Handling
4.1 Basic structure
While True:
Try
Print ("1212")
Except Exception as E:
Print ("Error")
4.2 Complete structure
While True:
Try
Print ("1212")
Except Exception as E:
Print ("Error")
Else
Print ("3434")
Finally
Print ("5656")
4.3 assertions
Assert condition
The condition is true to continue, otherwise the exception is actively thrown
4.4 Custom Exceptions
Class Ttterror (Exception):
def __init__ (self,message):
SELF.MSG = Message
Super (Ttterror,self). __INIT__ (Message)
Try
Name = "Alex"
If name! = "TTT":
Raise Ttterror ("You are not TTT") #主动抛出错误
Except Ttterror as E:
Print ("Ttterror", E)
Except Exception as E:
Print (e,111111)
Output:
Ttterror, you're not TTT.
5. Reflection
Cat Account
def login ():
Return "Please enter user name, password"
def logout ():
Return "Jump to login Screen"
From controller import account
While True:
Action = input (">>:")
if (hasattr (account,action)):
Func = GetAttr (account,action)
result = Func ()
Else
result = ' 404 '
Print (Result)
Output:
F:\Python\Python3\python.exe D:/python Training/our_python/day8/app.py
>>:login
Please enter user name, password
>>:logout
Jump to login screen
>>:asd
404
6. Socket programming
Mac is planar addressing, IP is level two addressing
Stand-alone mode------
Service side :
Import socket
Server = Socket.socket (socket.af_inet,socket. SOCK_STREAM) #AF_INET Sock_stream
Server.bind (("0.0.0.0", 8000))
Server.listen (5)
Print ("--start--")
CONN,CLIENT_ADDR = Server.accept ()
Print (CONN,CLIENT_ADDR)
While True:
data = CONN.RECV (1024x768) #最大接收1024字节
Print ("Recv from client:", data)
Conn.send (b "Got Msg")
Client:
Import socket
Client = Socket.socket ()
Client.connect (("localhost", 8000))
While True:
msg = input ("MSG>>:"). Strip ()
If Len (msg) = = 0:continue
Client.send (Msg.encode ())
Print ("SEND>>:", msg)
data = CLIENT.RECV (1024)
Print ("Receive from Server>>:", data)
concurrency mode:
Server side puts executed data into buffer, buffer full or send wait time timeout (typically in milliseconds)
Python Foundation article-day8