Can a method parameter have the same name as an instance variable?

Question

Can a parameter to a method have the same variable name as an instance variable for a class?

Answer

Although the parameter and instance variable may appear to share the same name, the instance variable is referenced using self. so they are actually two different variables even though they may appear similar. The following code example shows a method parameter name and an instance variable self.name. While they may appear to be similar, they are actually two different variables.

class Vars:

    def __init__(self):
        self.name = "Instance Var"

    def show(self, name):
        print("name = " + name)
        print("self.name = " + self.name)

test = Vars()

test.show("this is a parameter")

# OUTPUT:
# name = this is a parameter
# self.name = Instance Var
8 Likes