猿问

在单独的类中使用枚举

我正在编写一种实现银行帐户的方法。很简单,我希望输出的是用户的姓名和帐户类型。但是,我在主课中使用时遇到了问题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)

有没有办法做到这一点,如果我输入accountType1的BankAccount参数,它会返回


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


Cats萌萌
浏览 177回答 2
2回答

湖上湖

这只是一个猜测,因为我仍然不确定你在问什么。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):        return("The owner of this account is {} "               "and his account type is: {} ".format(                    self.owner, AccountType(self.accountType).name))#test the codetest = BankAccount("Max", 1)print(test)test2 = BankAccount("Mark", 2)print(test2)输出:The owner of this account is Max and his account type is: SAVINGSThe owner of this account is Mark and his account type is: CHECKING这样你就不必硬编码任何东西或创建self.d属性,因为它不再需要。

有只小跳蛙

您可以对硬编码的 1 in 应用__str__与accountTypein 相同的操作__init__:self.accountType = AccountType(accountType)即使您现在可以摆脱self.d并使用self.accountType,我还是建议不要在初始化中使用整数值:test = BankAccount("Max", AccountType.SAVINGS)这比使用幻数要清楚得多。更新__init__将接受枚举及其值。
随时随地看视频慕课网APP

相关分类

Python
我要回答