Python 3.6模块变量调用报错:无法访问函数内定义的变量
universal.py Module The error you’re hitting makes total sense—those usr, pwd, and account variables inside your functions are local variables. They only exist while the function runs, and they aren’t attached as attributes to the function itself. That’s why fb_acc.usr throws an error: the function object doesn’t have that property.
Here are a few practical fixes depending on what you need:
Option 1: Return Account Details as a Dictionary (Cleanest for Reusable Logic)
If you want to keep using functions (maybe you’ll add dynamic credential generation later), have the functions return your account info as a dictionary:
# universal.py def fb_acc(): return { 'usr': 'XXXX', 'pwd': 'XXXX' } def bank_acc(): return { 'accno': 'XXXX', 'ssc': 'XXX', 'pwd': 'XXXX' }
Then use it like this:
from universal import fb_acc # Call the function to get the full account data fb_account = fb_acc() usr = fb_account['usr'] pwd = fb_account['pwd']
Option 2: Use Module-Level Variables (Simplest for Static Credentials)
If your account info is just static values (no need for function logic), skip the functions entirely and define variables directly in the module:
# universal.py # Facebook account fb_usr = 'XXXX' fb_pwd = 'XXXX' # Bank account bank_accno = 'XXXX' bank_ssc = 'XXX' bank_pwd = 'XXXX'
Accessing them becomes straightforward:
from universal import fb_usr, fb_pwd usr = fb_usr pwd = fb_pwd
Option 3: Attach Variables as Function Attributes (Less Common)
If you really want to stick with functions and attribute access, you can assign values to the function itself inside the function body. Just remember to run the function first to initialize those attributes:
# universal.py def fb_acc(): # Assign values as properties of the function fb_acc.usr = 'XXXX' fb_acc.pwd = 'XXXX' def bank_acc(): bank_acc.accno = 'XXXX' bank_acc.ssc = 'XXX' bank_acc.pwd = 'XXXX'
Usage:
from universal import fb_acc # First call the function to create the attributes fb_acc() usr = fb_acc.usr pwd = fb_acc.pwd
Most folks would go with Option 1 or 2—Option 3 feels a bit hacky unless you have a specific use case for it.
内容的提问来源于stack exchange,提问作者Binh Nguyen

