Home > Enterprise >  Instantiating a class by passing self as argument
Instantiating a class by passing self as argument

Time:12-30

I came across some python examples where a class instance is created by Invoking the class and passing "self" to it. I cant seem to understand the meaning of it and when we would use such constructs.

Below is a sample extract, where a class is instantiated inside another class. I "think" I have also seen something like objA = Class_def(self). I cant recall where I saw that, so it would be good to know if its possible or not.

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

CodePudding user response:

Generally speaking, class is always passed to its method as an argument, this is the way they work. Although in e.x. C it is implicit, Python does that explicitly.

In BaseProtocol you are initializing members of BaseProtocol class. When initializing, self is redundant because constructor of IdleState method doesn't need access to its instance variables, so you can delete it. However if you are doing something with member IDLE, like calling method which is using its instance variables, you need to pass self.

Learn more: https://www.knowledgehut.com/blog/programming/self-variabe-python-examples

CodePudding user response:

It is absolutely possible to do that, as self is a default object passed by 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'
  • Related