通过将self作为参数传递来实例化类



我遇到了一些python示例,其中通过调用类并传递"自我;我似乎不明白它的含义,也不明白我们什么时候会使用这样的结构。

下面是一个示例摘录,其中一个类在另一个类中实例化。我"思考;我也见过类似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

一般来说,类总是作为参数传递给其方法,这就是它们的工作方式。虽然在e.x.C++中它是隐式的,但Python是显式的。

在BaseProtocol中,您正在初始化BaseProtocol类的成员。初始化时,self是多余的,因为IdleState方法的构造函数不需要访问其实例变量,所以您可以删除它。但是,如果您对成员IDLE执行某些操作,比如调用使用其实例变量的方法,则需要传递self

了解更多信息:https://www.knowledgehut.com/blog/programming/self-variabe-python-examples

这样做是绝对可能的,因为self是python-传递的默认对象

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'

最新更新