Declaring parameters/variables within the function

Hi, I had been coding for a while and sometimes I see despite some parameter not being declared within a function of a class. Still, some developers use self method to call them. Can anyone explain me how it works?

Code Snippet:

class Client:
    def __init__(self, host, port):

        self.sock =socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((host, port))

As it’s visible above, sock was not called through init method but still we’re able to use self for sock Can someone help me with this problem? I’ll be really grateful ^^

Hello, @stanfordblaze, and welcome to the Python Forum!

In this __init__ method header, self is specified as the first parameter:

    def __init__(self, host, port):

As a result, self represents the new instance of Client that is being initialized.

This statement adds an instance variable named sock to the new Client instance:

        self.sock =socket.socket(socket.AF_INET, socket.SOCK_STREAM)

The fact that sock was not supplied as a parameter in the __init__ header does not prevent its name from being added to the new Client instance to represent an instance variable.

Once that instance variable has been added, methods that are connected with its type can be called, and that is what happens here:

        self.sock.connect((host, port))