Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 下面的例子被认为是有效的吗?如果不是,怎么会更好呢?_Python_Python 3.x_Oop_Object - Fatal编程技术网

Python 下面的例子被认为是有效的吗?如果不是,怎么会更好呢?

Python 下面的例子被认为是有效的吗?如果不是,怎么会更好呢?,python,python-3.x,oop,object,Python,Python 3.x,Oop,Object,我是编程和面向对象编程的新手 下面是python代码的一部分,它运行得很好。我在open_bank_account()上硬编码了一些变量,用于测试 问题:会被认为是相当最优和高效的吗?如果没有,我可以在哪里改进代码? class Bank_Account: def __init__(self, account_id, account_pin, account_balance): self._account_id = account_id self._acc

我是编程和面向对象编程的新手

下面是python代码的一部分,它运行得很好。我在open_bank_account()上硬编码了一些变量,用于测试

问题:会被认为是相当最优和高效的吗?如果没有,我可以在哪里改进代码?

class Bank_Account:
    def __init__(self, account_id, account_pin, account_balance):
        self._account_id = account_id
        self._account_pin = account_pin
        self._account_balance = account_balance
        self._individual_bank_account_dicitionary = {}
        self._individual_bank_account_dicitionary[account_id] = {"Pin": account_pin, "Balance": account_balance}

    def get_bank_account_balance(self, account_id):
        return "Balance: ${:.2f}".format(self._individual_bank_account_dicitionary[account_id]["Balance"])

    def __str__(self):
        return "{}".format(self._individual_bank_account_dicitionary)

class Bank:
    def __init__(self, bank_name):
        self._bank_name = bank_name
        self._bank_dicitionary = {}

    def update_bank_dictionary(self, bank_account):
        self._bank_dicitionary[bank_account._account_id] = {"Pin": bank_account._account_pin, "Balance": bank_account._account_balance}

    # 1. A method to return the dictionary of bank accounts of the object from class Bank.
    # 2. In this case, only bank_1 from main() is the object argument.      
    def get_bank_dictionary(self):
        return self._bank_dicitionary

    # 1. Method to create object bank_account only when needed.
    def get_bank_account(self, account_id):
        account_pin = self._bank_dicitionary[account_id]["Pin"]
        account_balance = self._bank_dicitionary[account_id]["Balance"]
        bank_account = Bank_Account(account_id, account_pin, account_balance)
        return bank_account

    # 1. This is used to convert the dictionary into a string for printing purposes.
    def string_bank_dictionary(self):
        string_list = ["account ID: {} \naccount Pin: {} \nBank Balance: {} \n".format(key, self._bank_dicitionary[key]["Pin"], self._bank_dicitionary[key]["Balance"])\
                      for key, value in self._bank_dicitionary.items()]
        return "\n".join(string_list) 

    def __str__(self):
        return "{}".format(self.string_bank_dictionary())

def open_bank_account(bank):
#     # Uncomment out when running actual program.
#     account_id = input("Enter account id here: ")
#     account_pin = input("Enter account pin here: ")
#     account_balance = input("Enter account initial balance here: ")

    # Comment out when running actual program. 
    # Currently in used for testing purposes.
    account_id = 455
    account_pin = 123
    account_balance = 888
    bank_account = Bank_Account(account_id, account_pin, account_balance)
    bank.update_bank_dictionary(bank_account)

    # Comment out when running actual program.
    # Currently in used for testing purposes.
    account_id = 777
    account_pin = 777
    account_balance = 1
    bank_account = Bank_Account(account_id, account_pin, account_balance)
    bank.update_bank_dictionary(bank_account)

    # Comment out when running actual program. 
    # Currently in used for testing purposes.   
    account_id = 631
    account_pin = 222
    account_balance = 50
    bank_account = Bank_Account(account_id, account_pin, account_balance)
    bank.update_bank_dictionary(bank_account)

    return bank

def check_bank_blanance(bank):
    valid_id_password = False
    temporary_dictionary = bank.get_bank_dictionary()
    while True:
        account_id = int(input("Enter account id here: "))
        account_pin = int(input("Enter account pin here: "))
        for key in temporary_dictionary.keys():
            if account_id == key and temporary_dictionary[account_id]["Pin"] == account_pin:
                valid_id_password = True
                bank_account = bank.get_bank_account(account_id)
                print(bank_account.get_bank_account_balance(account_id))
                break
        if valid_id_password == True:
            break
        else:
            print("Invalid account id/password. Please try again.")

def main():
    bank_1 = Bank("ABC Bank")
    while True:
        print("Menu \n1. Open bank account \n2. Check balance")
        while True:
            account_choice = int(input("Enter option here: "))
            if account_choice <= 0 and account_choice >= 7:
                account_choice = int(input("Enter option here: "))
            else:
                break        
        if account_choice == 6:
            break
        elif account_choice == 1:
            bank_1 = open_bank_account(bank_1)
        elif account_choice == 2:
            balance = check_bank_blanance(bank_1)

main()
class银行账户:
定义初始(自我、账户id、账户pin、账户余额):
self.\u account\u id=account\u id
self.\u account\u pin=account\u pin
自身账户余额=账户余额
自我.(个人)(银行)(账户)(存款)={}
self._个人_银行_账户_dictionary[account_id]={“Pin”:account_Pin,“Balance”:account_Balance}
def获取银行账户余额(自身、账户id):
返回“余额:${:.2f}”。格式(self.\u个人\银行\账户\存款[账户id][“余额”])
定义(自我):
返回“{}”。格式(自我、个人、银行、账户、决定)
银行类别:
定义初始(自我、银行名称):
self.\u bank\u name=银行名称
自我。_bank_dictionary={}
def更新银行词典(自助、银行账户):
self._bank_dictionary[银行账户._账户id]={“Pin”:银行账户。_账户_Pin,“余额”:银行账户。_账户_余额}
# 1. 从类bank返回对象的银行帐户字典的方法。
# 2. 在本例中,只有bank_1 from main()是对象参数。
def get_bank_字典(自我):
返回自我。银行决定
# 1. 方法仅在需要时创建对象银行帐户。
def get_银行账户(自身、账户id):
账户密码=自身银行密码[账户密码][“密码”]
账户\余额=自身。\银行\存款人[账户\ id][“余额”]
银行账户=银行账户(账户id、账户pin、账户余额)
返回银行账户
# 1. 这用于将字典转换为字符串以便打印。
def string_bank_字典(self):
string_list=[“帐户ID:{}\n帐户Pin:{}\n银行余额:{}\n”。格式(key,self.\u bank_dictionary[key][“Pin”],self.\u bank_dictionary[key][“Balance”])\
对于键,使用self中的值。_bank_dictionary.items()]
返回“\n”。加入(字符串列表)
定义(自我):
返回“{}”.format(self.string\u bank\u dictionary())
def开户银行账户(银行):
##运行实际程序时取消注释。
#账户id=输入(“在此处输入账户id:”)
#账户密码=输入(“在此处输入账户密码:”)
#账户\余额=输入(“在此处输入账户初始余额:”)
#在运行实际程序时注释掉。
#目前用于测试目的。
账户id=455
账户pin=123
账户余额=888
银行账户=银行账户(账户id、账户pin、账户余额)
银行。更新银行字典(银行账户)
#在运行实际程序时注释掉。
#目前用于测试目的。
账户id=777
账户密码=777
账户余额=1
银行账户=银行账户(账户id、账户pin、账户余额)
银行。更新银行字典(银行账户)
#在运行实际程序时注释掉。
#目前用于测试目的。
账户id=631
账户pin=222
账户余额=50
银行账户=银行账户(账户id、账户pin、账户余额)
银行。更新银行字典(银行账户)
回程银行
def支票银行票据(银行):
有效的\u id\u密码=错误
临时字典=bank.get\u bank\u字典()
尽管如此:
帐户id=int(输入(“在此处输入帐户id:”)
account_pin=int(输入(“在此处输入account pin:”))
对于临时字典中的键。键():
如果帐户id==密钥和临时字典[帐户id][“Pin”]==帐户Pin:
有效的\u id\u密码=真
银行账户=银行。获取银行账户(账户id)
打印(银行账户。获取银行账户余额(账户id))
打破
如果有效的\u id\u密码==True:
打破
其他:
打印(“无效的帐户id/密码。请重试。”)
def main():
银行1=银行(“ABC银行”)
尽管如此:
打印(“菜单\n1.开立银行账户\n2.检查余额”)
尽管如此:
account_choice=int(输入(“在此处输入选项:”)
如果账户选择=7:
account_choice=int(输入(“在此处输入选项:”)
其他:
打破
如果账户_选项==6:
打破
elif账户_选项==1:
银行1=开立银行账户(银行1)
elif账户_选项==2:
余额=支票银行贷款(银行1)
main()
这个程序运行得很好。如果我能更好、更有效地编写代码,我想寻求改进的指针

我只设计并保留了一个主要对象();i、 e.第一银行;它包含多个银行帐户信息的字典。我已选择仅在open_bank_account()中创建对象bank_account,并仅在需要时检查_bank_blanance(),这些对象在函数完成后消失

这里的目的是在main()上保留尽可能少的可用对象。


没有遇到错误。程序运行正常;只需输入,然后输入,然后输入,然后再输入。它将打印账户id 777中1.00美元的银行账户余额。

这将更适合您的问题:@ParthS007感谢您为我指出正确的去处。谢谢字典的一个主要优点是O(1)查找键,因此在键上循环只需使用类似于
if account\u id in temp\u dict和temp\u dict[account\u id][“pin”]==pin: