亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在單獨的類中使用枚舉

在單獨的類中使用枚舉

Cats萌萌 2021-06-18 22:51:04
我正在編寫一種實現銀行帳戶的方法。很簡單,我希望輸出的是用戶的姓名和帳戶類型。但是,我在主課中使用時遇到了問題Enum。from enum import Enumclass AccountType(Enum):    SAVINGS = 1    CHECKING = 2#bank account classes that uses AccountTypeclass BankAccount():    def __init__(self, owner, accountType):        self.owner = owner        self.accountType = accountType    def __str__(self):        self.d = AccountType(1)        return "The owner of this account is {} and his account type is: {} ".format(self.owner, self.d)#test the codetest = BankAccount("Max", 1)print(test)輸出The owner of this account is Max and his account type is: AccountType.SAVINGS所以這是所需的輸出,但這僅在我對__str__方法 ( AccountType(1)) 中的帳戶類型進行硬編碼時才有效。為了澄清,我的意思是這一行:BankAccount("Max", 1)有沒有辦法做到這一點,如果我輸入accountType1的BankAccount參數,它會返回The owner of this account is Max and his account type is: AccountType.SAVINGS
查看完整描述

2 回答

?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

這只是一個猜測,因為我仍然不確定你在問什么。


from enum import Enum


class AccountType(Enum):

    SAVINGS = 1

    CHECKING = 2


#bank account classes that uses AccountType

class BankAccount:

    def __init__(self, owner, accountType):

        self.owner = owner

        self.accountType = accountType


    def __str__(self):

        return("The owner of this account is {} "

               "and his account type is: {} ".format(

                    self.owner, AccountType(self.accountType).name))


#test the code

test = BankAccount("Max", 1)

print(test)

test2 = BankAccount("Mark", 2)

print(test2)

輸出:


The owner of this account is Max and his account type is: SAVINGS

The owner of this account is Mark and his account type is: CHECKING

這樣你就不必硬編碼任何東西或創建self.d屬性,因為它不再需要。


查看完整回答
反對 回復 2021-06-29
?
有只小跳蛙

TA貢獻1824條經驗 獲得超8個贊

您可以對硬編碼的 1 in 應用__str__accountTypein 相同的操作__init__

self.accountType = AccountType(accountType)

即使您現在可以擺脫self.d并使用self.accountType,我還是建議不要在初始化中使用整數值:

test = BankAccount("Max", AccountType.SAVINGS)

這比使用幻數要清楚得多。更新__init__將接受枚舉及其值。


查看完整回答
反對 回復 2021-06-29
  • 2 回答
  • 0 關注
  • 197 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號