今天看到狀態機的部分,然后書中提到可以簡化代碼,然后有了下面的老方案 和新方案,然后有了下面4塊疑惑(新方案說實話感覺像看天書,完全一臉懵逼,怎么就新方案簡化代碼了完全沒明白),各位大俠能幫忙解釋下相關的一些代碼的含義嗎,非常感謝
""" 老方案,好多個判斷陳述句,效率低下"""
class Connection:
def __init__(self):
self.state = 'CLOSED'
def read(self):
if self.state != 'OPEN':
raise RuntimeError('Not open')
print('reading')
def write(self, data):
if self.state != 'OPEN':
raise RuntimeError('Not open')
print('writing')
def open(self):
if self.state == 'OPEN':
raise RuntimeError('Already open')
self.state = 'OPEN'
def close(self):
if self.state == 'CLOSED':
raise RuntimeError('Already closed')
self.state = 'CLOSED'
""" 新方案——對每個狀態定義一個類,Connection1類為主類"""
class Connection1:
def __init__(self):
self.new_state(ClosedConnectionState) # 疑惑1 這段代碼是什么含義,new_state 和 ClosedConnectionState 表示什么
def new_state(self, newstate): # 疑惑2 這段代碼的目的又是什么
self._state = newstate
def read(self):
#呼叫的是所屬實體的方法(Close/Open)
return self._state.read(self)
def write(self, data):
return self._state.write(self, data)
def open(self):
return self._state.open(self)
def close(self):
return self._state.close(self)
class ConnectionState: # 疑惑3 其實這整塊的class ConnectionState: 都沒明白含義
@staticmethod # 疑惑4 staticmethod 是對應上面的哪部分
def read(conn):
#子類必須實作父類的方法,否則報下列錯誤
raise NotImplementedError()
@staticmethod
def write(conn, data):
raise NotImplementedError()
@staticmethod
def open(conn):
raise NotImplementedError()
@staticmethod
def close(conn):
raise NotImplementedError()
class ClosedConnectionState(ConnectionState): # 疑惑5 這是關聯上面的 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')
class OpenConnectionState(ConnectionState):
@staticmethod
def read(conn):
print('reading')
@staticmethod
def write(conn, data):
print('writing')
@staticmethod
def open(conn):
raise RuntimeError('Already open')
@staticmethod
def close(conn):
#轉換為Close實體,呼叫父類的new_state方法
conn.new_state(ClosedConnectionState)
uj5u.com熱心網友回復:
可以看我的博客,輔助理解uj5u.com熱心網友回復:
https://blog.csdn.net/hbu_pig/article/details/80808896uj5u.com熱心網友回復:
你這是好多的面向物件的語法基礎知識都沒看,就在看程式建議先看看類,類的繼承,類的靜態方法和類方法及實體方法
python一切皆物件
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/202813.html
