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__
将接受枚举及其值。
添加回答
举报