我遇到了一些 python 示例,其中通過呼叫類并將“self”傳遞給它來創建類實體。我似乎無法理解它的含義以及我們何時會使用此類構造。
下面是一個示例摘錄,其中一個類在另一個類中實體化。我“認為”我也見過類似的東西objA = Class_def(self)。我不記得我在哪里看到的,所以最好知道它是否可能。
class BaseState(object):
def __init__(self, protocol):
self.protocol = protocol
def connect(self, request):
state = self.__class__.__name__
class IdleState(BaseState):
def connect(self, request):
return self.protocol.doConnect(request)
class ConnectingState(BaseState):
def handleCONNACK(self, response):
self.protocol.handleCONNACK(response)
class ConnectedState(BaseState):
def disconnect(self, request):
self.protocol.doDisconnect(request)
class BaseProtocol(Protocol):
def __init__(self, factory):
###
# what is happening here -
###
self.IDLE = IdleState(self)
self.CONNECTING = ConnectingState(self)
self.CONNECTED = ConnectedState(self)
self.state = self.IDLE
uj5u.com熱心網友回復:
一般來說,類總是作為引數傳遞給它的方法,這就是它們的作業方式。盡管在 ex C 中它是隱式的,但 Python 顯式地做到了這一點。
在 BaseProtocol 中,您正在初始化BaseProtocol類的成員。初始化時,self是多余的,因為 IdleState 方法的建構式不需要訪問它的實體變數,所以你可以洗掉它。但是,如果您正在對 member 執行某些操作IDLE,例如呼叫使用其實體變數的方法,則需要通過self.
了解更多:https : //www.knowledgehut.com/blog/programming/self-variabe-python-examples
uj5u.com熱心網友回復:
絕對有可能這樣做,因為selfpython傳遞的默認物件也是如此-
class a:
def __init__(self,__self,x):
self.x=x
print(self.x) #the local x that is passed into the object
print(__self.x) #the x that is in the self that is passed into the object
class b:
def __init__(self,x):
self.x=x
obj=a(self,'foo')
obj=b('baz') #should print 'foo', then 'baz'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/399046.html
