(Python 3.6) Can't not use variable in module

Binh Nguyen Source

This is my module storing my account information for easy-access in further project.

#universal.py

def fb_acc():
    usr = XXXX
    pwd = XXXX
def bank_acc():
    accno = XXXX
    ssc = XXX
    pwd = XXXX

However, when I tried to use to put these variables in the local variable, it reported like this:

>> from universal import fb_acc
>> usr = fb_acc.usr
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
usr = fb_acc.usr
AttributeError: 'function' object has no attribute 'usr'

Can anyone help my point my syntax errors in 2 scripts?

pythonpython-3.x

Answers

answered 5 months ago Daniele Cappuccio #1

The usr variable is defined within the fb_acc function, and this means that you cannot access them from the outside (except in some special cases).

Functions have no variables: they are part of code that take some parameters, do some stuff and return a result. Every variable you declare in the function is intended to be used only from that function and to make programmer's life easier.

You should go with a class instead, like this:

class fb_acc:  
    def __init__(self):
        self.usr = XXXX
        self.pwd = XXXX
    def __repr__(self):
        return 'usr = {}, pwd = {}'.format(self.usr, self.pwd)

foo = fb_acc()
usr = foo.usr

comments powered by Disqus