我正在编写一种实现银行帐户的方法。这很简单,我希望输出为用户的名称和帐户类型。但是,我在主班上使用Enum
时遇到问题。
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):
self.d = AccountType(1)
return "The owner of this account is {} and his account type is: {} ".format(self.owner, self.d)
#test the code
test = 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)
有没有办法做到这一点,如果我在accountType的1
参数中输入BankAccount
,它将返回
The owner of this account is Max and his account type is: AccountType.SAVINGS
答案 0 :(得分:1)
这只是一个猜测,因为我仍然不确定您要问什么。
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
属性,因为它不再需要。
答案 1 :(得分:0)
您可以对__str__
中的硬编码1到accountType
中的__init__
应用相同的操作:
self.accountType = AccountType(accountType)
即使您现在可以摆脱self.d
并使用self.accountType
,我还是建议不要在初始化中使用整数值开头:
test = BankAccount("Max", AccountType.SAVINGS)
这比使用幻数更清楚。对__init__
的更新将同时接受枚举及其值。