r_hudson
r_hudson

Reputation: 193

Python assign local value to attribute in imported module

In Script1 I've defined class1.

To initiate class1, you just need one variable x, but it has other attribute y which is not required to initiate the class. When I run script 1, it assigns value 10 to y which is declared after if __name__ == __main__: line.

######Script1#########
Class class1:
    def __init__(self,x):
        self.x = x
        self.y = y
if __name__ == '__main__':
    y = 10
    class_instance = class1(100)
    print(class_instance.y) #prints 10 or assigns 10 to class.y

In script2 I import class1 and try to assign value to y, but it gives me NameError. I tried declaring y as global in class1, and few other things but it is not working. I understand it has something to do with namespace and scoping - any pointer in right direction will be of great help. Thanks.

#### script2 ######
from script1 import *
if __name__ == '__main__':
    y = 10
    class_instance = class1(200)
    print(class_instance.y) #gives NameError
NameError: name 'y' is not defined

Upvotes: 0

Views: 50

Answers (1)

Alan Hoover
Alan Hoover

Reputation: 1450

What you want here is an optional keyword argument (https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments):

Class class1:
    def __init__(self,x, y=10):
        self.x = x
        self.y = y
if __name__ == '__main__':
    class_instance = class1(100)
    print(class_instance.y)              #prints 10 

    instance2 = class1(100,200)
    print(instance2.y)                   #prints 200 

    instance3 = class1(100,y=300)
    print(instance3.y)                   #prints 300 

This will allow you to supply the y value if you wish. If you do not supply the y value, it will use the default of 10.

Upvotes: 2

Related Questions