在单独的类中使用枚举

时间:2018-09-27 00:29:19

标签: python python-3.x

我正在编写一种实现银行帐户的方法。这很简单,我希望输出为用户的名称和帐户类型。但是,我在主班上使用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

2 个答案:

答案 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__的更新将同时接受枚举及其值。