我写了一个程序,我试图把我的程序分成多个python文件。但是它返回未知属性Error,我不知道如何解决。
我的代码有五个部分。第一部分叫做数据库,这是我自己的数据库,里面有一些非真实的数据。
from pymongo import MongoClient
from bson import ObjectId
client = MongoClient(
sample.com # I hide my MongoDB account in here for security reason
)
db = client.Peter
user = db['User']
tx = db['Transaction']
db.User.drop()
db.Transaction.drop()
# Create
creative = [{'name': 'Peter', 'balance': 52642},
{'name': 'Mary', 'balance': 57127},
{'name': 'John', 'balance': 9000},
{'name': 'Terry', 'balance': 29000},
{'name': 'Tom', 'balance': 350000},
{'name': 'Jason', 'balance': 21000},
{'name': 'Ken', 'balance': 41400},
{'name': 'Eva', 'balance': 21600}]
fake_record = [{'name': 'Peter', 'Transaction Type': 'Revenue', 'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'Mary', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'Mary', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'John', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'John', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'John', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'Terry', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'Terry', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'Terry', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'Terry', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'Tom', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'Tom', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'Tom', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'Jason', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'Jason', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'Jason', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'Ken', 'Transaction Type': 'Revenue',
'Transaction Category': 'Food', 'Transaction amount': 52642},
{'name': 'Eva', 'Transaction Type': 'Revenue', 'Transaction Category': 'Food', 'Transaction amount': 52642}]
db.User.insert_many(creative)
db.Transaction.insert_many(fake_record)
第二部分,下面的文件是我的主程序。
from database import user, tx
import getpass
import inquirer
import time
from view import View
from store import Store
def main():
print("Welcome to The Goldman Sachs Group Banking System !!!")
p = getpass .getpass("Please enter your password : ")
if (p == 'sunday'):
view1 = View()
view1.first_page()
if __name__ == '__main__':
main()
第3部分,下面的代码是我的视图程序,它包含我拥有的所有屏幕(页面)。如果这个程序的用户运行这个程序,他们将浏览下面的一些页面,我将让他们选择我给他们的一些选项。
import inquirer
import time
from model import Player
from database import user, tx
from store import Store
import route
class View:
def __init__(self) -> None:
self.player = Player()
self.route = route.Route()
self.store = Store()
def first_page(self) -> None:
# Question Section
questions = [
inquirer.List('page_1_result',
message="What do you want to do?",
choices=['Continue With Existing User',
'Create New Player'],
),
]
answer = inquirer.prompt(questions)
# Answer Section
if answer['page_1_result'] == 'Continue With Existing User':
self.current_user = self.player.enterOldPlayers()
else:
self.current_user = self.player.createNewPlayer()
self.store.setUserName(self.current_user)
# Routing
self.route.goTo1()
def second_page(self):
# Question Section
print(f"Hello {str(self.store.getUserName())},n")
questions = [
inquirer.List('Please Choose Action',
message=f"What do you want to do?",
choices=['View all transaction',
'Add Tansaction',
'Back to previous page'],
),
]
answer1 = inquirer.prompt(questions)
# Answer Section
if answer1['Please Choose Action'] == 'Add Tansaction':
self.route.goTo("Page 3 c1")
elif answer1['Please Choose Action'] == 'View all transaction':
self.route.goTo("Page 4")
else:
self.route.goTo("Page 1")
def third_page(self):
questions = [
inquirer.List('Please Choose a type',
message="Please Choose a type",
choices=['Revenue',
'Expense',
'Back to previous page'],
),
]
self.transaction_type = answer1 = inquirer.prompt(questions)
# Back to second page if they chosen this answer
if answer1['Please Choose a type'] == 'Back to previous page':
self.route.goTo("Page 2")
self.route.goTo("Page 3__v2")
def third_page_v2(self):
questions = [
inquirer.List('Please Choose a category',
message="Please Choose a category",
choices=['Food',
'Transportation',
'Rent',
'Back to previous page'],
),
]
self.transaction_category = answer1 = inquirer.prompt(questions)
if answer1['Please Choose a category'] == 'Back to previous page':
self.route.goTo("Page 3")
else:
self.route.goTo("Page 3__v3")
def third_page_v3(self):
self.amount = float(
input('Please enter a amount for the transaction:'))
if self.amount != '':
self.route.goTo("Page 3__v4")
def third_page_v4(self):
dummy1 = user.find_one({'name': self.store.getUserName()})
questions = [
inquirer.List('Confirm',
message="Did you confirmed all the data inputed is correct?",
choices=['Yes',
'No, bring me back to the previous page', ]
),
]
answer1 = inquirer.prompt(questions)
if answer1['Confirm'] == 'Yes':
tx.insert_one(
# transaction_type['Please Choose a type'] << This line was used to obtained the value
{'name': dummy1['name'],
'Transaction Type': self.transaction_type['Please Choose a type'],
'Transaction Category': self.transaction_category['Please Choose a category'],
'Transaction Amount': self.amount}
)
# Update Balance
balance = dummy1['balance']
if self.transaction_type['Please Choose a type'] == 'Revenue':
balance += self.amount
user.update_one({'name': dummy1['name']}, {
"$set": {'balance': (balance)}})
else:
balance -= self.amount
user.update_one({'name': dummy1['name']}, {
"$set": {'balance': (balance)}})
# TODO: ADD A {} in that set of data
print(
f"You have entered a entry with ---> {self.transaction_type['Please Choose a type']}, {self.transaction_category['Please Choose a category']}, {self.amount}")
print("The database has been updated, you will be sent to the first page")
time.sleep(1.5)
self.route.goTo("Page 1")
else:
self.route.goTo("Page 3__v2")
def fourth_page(self):
transactions = tx.find({'name': self.store.getUserName()})
for transaction in transactions:
print(transaction)
print("All transaction has been shown from the database.")
time.sleep(1.5)
questions = [
inquirer.List('back_or_not',
message="Do you want to go back to previous page?",
choices=['Yes',
'No, bring me back to the first page', ]
),
]
answer1 = inquirer.prompt(questions)
self.go_back_or_not = answer1
if self.go_back_or_not['back_or_not'] == 'Yes':
self.route.goTo("Page 2")
else:
self.route.goTo("Page 1")
第4部分,下面的代码是我的路由,它告诉这个程序的用户在运行这个程序时会去哪个页面。
import view
class Route:
def goTo(self, temp):
if temp == "Page 2":
self.user1 = view.View().current_user
self.screen = view.View().second_page()
return self.screen
if temp == "Page 3":
self.transaction_type = view.View().third_page()
return self.transaction_type
if temp == "Page 4":
self.go_back_or_not = view.View().fourth_page()
return self.go_back_or_not
if temp == "Page 1":
self.screen = view.View().first_page()
return self.screen
if temp == "Page 3__v2":
self.transaction_category = view.View().third_page_v2()
return self.transaction_category
if temp == "Page 3__v3":
self.screen = view.View().third_page_v3()
return self.screen
if temp == "Page 3__v4":
self.screen = view.View().third_page_v4()
return self.screen
def goTo1(self):
self.screen = view.View().second_page()
return self.screen
第5部分,下面的代码称为模型。而是让用户决定是否"使用旧播放器"。或者"创建新用户";当他们运行这个程序时。这部分只有一个简单的函数。
from database import user, tx
import inquirer
class Player:
def createNewPlayer(self):
balance = 0
name = str(input('Please enter a name for the new user:').capitalize())
balance = float(
input('Please enter a balance amount for the new User:'))
new_user = {"name": name, "balance": balance}
user.insert_one(new_user)
return name
def enterOldPlayers(self):
users = user.find().sort("name")
questions = [
inquirer.List('user_selected',
message="Select a User",
choices=[user['name'] for user in users]
),
]
answer1 = inquirer.prompt(questions)
return answer1['user_selected']
第6部分,下面的代码调用了store。我想让这部分充当服务器。如果用户输入一些变量。我想保存这里所有的变量。当我想要回调这些变量时,我可以调用这部分的所有变量
例如,当用户运行这个程序时,他们需要选择一个玩家(即一个帐户)。然后我要保存他们选择的帐户名,并在程序的每一页打印出他们的名字。
class Store:
def __init__(self) -> None:
pass
def setUserName(self, username):
self.username = username
def getUserName(self):
return self.username
问题来了:当我试图运行App.py(我的程序的主要部分)时,它显示"AttributeError: 'Store'对象没有属性'username'"在名为"store"的文件中,其中包含第6部分中的代码。也就是getusernameeturn self.username"中的第9行。
我知道为什么这个错误会发生。这可能是因为当我运行第3部分的代码时,我已经清除了在self行中存储的变量。store = store ()".
因为我故意将一个非常大的文件分成多个文件,就像这些例子一样。如果我想保留我拥有的这六个部分的文件,我应该怎么做来解决这个问题?
我知道在Java Script中,有一个叫做"状态管理"的系统;可以解决这个问题。但是我不知道如何在Python中解决它。
非常感谢!
最好在类的__init__
方法中设置任何类属性。
如果您不这样做,并且在设置属性之前引用该属性,您将得到一个AttributeError
。
这段代码比较安全;如果你试图在用户名设置之前获取它,它将返回None,这是一个很大的线索,说明你还没有设置用户名。
class Store:
def __init__(self) -> None:
self.username = None
def setUserName(self, username):
self.username = username
def getUserName(self):
return self.username