简体   繁体   中英

How to create an object of a class present in one file from another file?

I have two files f1.py & f2.py .

f1.py contains a class C1 .

f2.py contains a class C2 which inherits C1 .

C1 containts a constructor

def __init__ (self, user_name, user_password, db_name):

    self.user_name = user_name
    self.user_password = user_password
    self.db_name = db_name

& a method

 def m1(self):
    print user_name

I create an object in f2 .

db3 = C2(user_name, user_password, db_name)
db3.conn_establish()

Where, all the passed parameters are assigned some value

If C2 was present in the same file as C1 . This would return no error. But, since C2 is present in another file. I get an error

NameError: global name 'user_name' is not defined

To overcome which I have to change m1 to: (just a workaround I found)

def m1(self):
    print self.user_name

Why did adding self work?

The workaround you found is the right way to implement this. The self argument is in fact the object reference you use to store and retrieve information from. If you don't use self, you are using a static variable and therefore you will have trouble if you create multiple instances of C1 (it's shared). Using self will force to check the instance's value (in either the class itself or from another class and/or file).

Shouldn't your function definition be:

 def m1(self):
    print self.user_name

Otherwise you are just printing some global value of user_name . I assume that such a value is present in f1.py which doesn't raise an error when both are present in the same file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM