我遇到了问题,或者我根本就不明白。 我想使用外部函数制作几个示例对象。 然后我想从外面访问它们。 在以下代码中:
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
我能以某种方式使这个例子工作吗?
答案 0 :(得分:0)
这是关于变量的范围。 [''.join(chr(ord(ch)+2) for ch in string) for string in plain]
只能在功能块中访问,因此您无法在功能外访问它。
我不知道你为什么要这样做,但一个解决方案是让user1成为一个全局变量:
user1