如何使用外部函数制作示例 class 对象并从外部访问它。 Python3.6

How to make example class object using outside function and acces it from outside. Python3.6

我有问题或者我根本不明白。 我想使用外部函数制作几个示例对象。 然后我想从外面访问它们。 在以下代码中:

class User():
    def __init__(self,id,name,email,password):
        self.id = id 
        self.name = name
        self.email = email
        self.password = password
        print('User created.')

class Category():
    def __init__(self,id,category):
        self.id = id
        self.category = category
        print('Category created.')

class Expenditure():
    def __init__(self,id,category,price,date):
        self.id = id
        self.category = category
        self.price = price
        self.date = date
        print('Expenditure created.')

def example_data():
    """Create example data for the test database."""
    user1 = User("1", 'Daniel', 'dany@gmail.com', 'pass')
    user2 = User(id="1", name='Daniel', email='dany@gmail.com', password='pass')
    cat1 = Category(id="1", category="Food")
    cat2 = Category(id="2", category="Flat")
    expense1 =  Expenditure(id="1", category=cat1.category, price=120, date="2017-12-01")
    expense2 =  Expenditure(id="2", category=cat2.category, price=230, date="2018-11-08")

example_data()
print(user1.name)

在这段代码之后我有 NameError:

print(user1.name)
NameError: name 'user1' is not defined

我可以使这个示例以某种方式工作吗?

这是关于变量范围的。 user1 只能在函数块中访问,因此您无法在函数外访问它。

我不知道你为什么要这样做,但一个解决方案是让 user1 成为一个全局变量:

def example_data():
    """Create example data for the test database."""
    global user1
    user1 = User("1", 'Daniel', 'dany@gmail.com', 'pass')
example_data()
print(user1.name)