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屬性,因為它不再需要。

TA貢獻1824條經驗 獲得超8個贊
您可以對硬編碼的 1 in 應用__str__
與accountType
in 相同的操作__init__
:
self.accountType = AccountType(accountType)
即使您現在可以擺脫self.d
并使用self.accountType
,我還是建議不要在初始化中使用整數值:
test = BankAccount("Max", AccountType.SAVINGS)
這比使用幻數要清楚得多。更新__init__
將接受枚舉及其值。
添加回答
舉報