"" "the old scheme, a lot of a statement, inefficient "" "
The class Connection:
Def __init__ (self) :
The self. The state='CLOSED'
Def read (self) :
If the self state!='OPEN' :
Raise RuntimeError (' Not open ')
Print (' reading ')
Def write (self, data) :
If the self state!='OPEN' :
Raise RuntimeError (' Not open ')
Print (' writing ')
Def open (self) :
If self. State=='OPEN' :
Already raise RuntimeError (' open ')
The self. The state='OPEN'
Def close (self) :
If the self. The state=='CLOSED' :
Raise RuntimeError (' Already closed ')
The self. The state='CLOSED'
"" "the new scheme, for each state defines a class, class Connection1 is the "" "
The class Connection1:
Def __init__ (self) :
Self. New_state (ClosedConnectionState) doubt # 1 this code is what meaning, what new_state and ClosedConnectionState said
Def new_state (self, newstate because) : # wondering what is the purpose of this code 2
Self. _state=newstate because
Def read (self) :
# call is subordinate to the instance methods (Close/Open)
Return the self. _state. Read (self)
Def write (self, data) :
Return the self. _state. Write (self, data)
Def open (self) :
Return the self. _state. Open (self)
Def close (self) :
Return the self. _state. Close (self)
Class ConnectionState: # doubt 3 actually this whole class ConnectionState: don't understand meaning
@ # staticmethod wondering what part 4 staticmethod is corresponding to the above
Def read (conn) :
# subclasses must implement methods of the parent, or report the following error
Raise NotImplementedError ()
@ staticmethod
Def write (conn, data) :
Raise NotImplementedError ()
@ staticmethod
Def open (conn) :
Raise NotImplementedError ()
@ staticmethod
Def close (conn) :
Raise NotImplementedError ()
Class ClosedConnectionState (ConnectionState) : # doubts this is associated with the above ClosedConnectionState?
@ staticmethod
Def read (conn) :
Raise RuntimeError (' Not open ')
@ staticmethod
Def write (conn, data) :
Raise RuntimeError (' Not open ')
@ staticmethod
Def open (conn) :
Conn. New_state (OpenConnectionState)
@ staticmethod
Def close (conn) :
Raise RuntimeError (' Already closed ')
The class OpenConnectionState (ConnectionState) :
@ staticmethod
Def read (conn) :
Print (' reading ')
@ staticmethod
Def write (conn, data) :
Print (' writing ')
@ staticmethod
Def open (conn) :
Already raise RuntimeError (' open ')
@ staticmethod
Def close (conn) :
# into the Close instance, call the superclass method new_state
Conn. New_state (ClosedConnectionState)
CodePudding user response:
Can see my blog, auxiliary understandingCodePudding user response:
https://blog.csdn.net/hbu_pig/article/details/80808896CodePudding user response:
You this is a lot of the object-oriented basic knowledge of grammar can't see, just looking at the programAdvice first take a look at class, inheritance, class of static methods and class methods and instance methods
Everything python objects