user3656142
user3656142

Reputation: 467

When I pass a parameter to a class constructor, are those made available to the other functions by the same name or self is needed?

Suppose I have a parameter which is passed to create an object of the class:

class Num1():
    def __init__(self, parameter1):
        self.param1 = parameter1

So now I have a class variable called param1 which can be accessed as self.param1 inside the class. But as we have also passed a parameter that we called parameter1 in the constructor, can we refer to that using the variable name parameter1 in a different method within the class?

In short, which among the two written below is correct?

def method1(self, parameter1)
def method1(self, self.param1)

when method1 is a method of the same class?

Upvotes: 0

Views: 147

Answers (2)

Matthew Gaiser
Matthew Gaiser

Reputation: 4763

Neither is correct. You do not need to add it to the arguments of the method to access it, but you do need to use self when referring to it.

This is the correct way:

def method3(self):
    print(self.param1)

Upvotes: 2

Gelineau
Gelineau

Reputation: 2090

Within the class, the parameter is accessible as self.param1. But you should not add it to the methods' signatures.

So the answer is:

def method1(self):
    print(self.param1)

Upvotes: 2

Related Questions