我撰寫了一個程式,并試圖將我的程式溢位到多個 python 檔案中。但它回傳我不知道如何解決的未知屬性錯誤。
我的代碼有五個部分。第一部分叫做Database,是我自己的資料庫,里面有一些非真實的資料。
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)
第2部分,下面的檔案是我的主要程式。
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(我程式的主要部分)時,它在名為“Store”的檔案中顯示“AttributeError: 'Store' object has no attribute 'username'”,這是代碼在第 6 部分。即第 9 行,在“getUserNamereturn self.username”中。
我對為什么會發生此錯誤有所了解。這可能是因為當我在“self.store = Store()”行中運行代碼的第 3 部分中的代碼時,我已經清除了存盤的變數。
由于我故意將一個非常大的檔案分成多個檔案,就像這些示例一樣。如果我想保留我擁有的這六部分檔案,我應該怎么做才能解決這個問題?
我知道在Java Script 中有一個叫做“狀態管理”的系統可以解決這個問題。但我不知道如何在 Python 中解決它。
非常感謝你!
uj5u.com熱心網友回復:
在類的方法中設定任何類屬性是一種很好的做法__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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/480897.html
