Python,无法在类外调用初始参数

The below python class have empty dictionary as initial arguments, after calling createAccount() outside class it successfully add data to dictionary but I can't access dictionary outside class.

我应在以下代码中进行哪些更改以访问新创建的帐户详细信息?

*请注意,我的错误发生在代码的最后一行*

class SavingsAccount():
    def __init__(self):
        self.savingsAccounts = {}
    def createAccount(self, name, initialDeposit):
        print()
        self.accountNumber = int(12345)
        self.savingsAccounts[self.accountNumber] = [name, initialDeposit]
        print("Account creation has been successful. Your account number is ", self.accountNumber)


SavingsAccount().createAccount(name = 'a',initialDeposit=4)

print(SavingsAccount().savingsAccounts[12345]) # getting error here
评论
  • 洛可可
    洛可可 回复

    You are creating a new instance of SavingsAccount with every call. After you call to createAccount completes, that instance is garbage-collected, as there are no references to it stored anywhere.

    s = SavingsAccount()
    
    s.createAccount(name='a', initialDeposit=4)
    print(s.savingsAccounts[12345])
    
  • vvelit
    vvelit 回复

    You should initialize your object using __init__,

    class SavingsAccount:
        def __init__(self, name, initial_deposit):
            self.savingsAccounts = {}
            self.accountNumber = int(12345)
            self.savingsAccounts[self.accountNumber] = [name, initial_deposit]
            print("Account creation has been successful. Your account number is ", self.accountNumber)
    
    
    saving_account = SavingsAccount(name='a', initial_deposit=4)
    
    print(saving_account.savingsAccounts)
    

    而且,大多数Pythonista使用者在命名变量时更喜欢snake_casing。