代码之家  ›  专栏  ›  技术社区  ›  Workhorse

在单独的类中使用枚举

  •  -1
  • Workhorse  · 技术社区  · 6 年前

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

    有没有办法让我进去的时候 1 进入 BankAccount

    此帐户的所有者是Max,其帐户类型为:AccountType.SAVINGS

    2 回复  |  直到 6 年前
        1
  •  1
  •   martineau    6 年前

    这只是猜测,因为我还不确定你到底在问什么。

    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

        2
  •  0
  •   Mad Physicist    6 年前

    您可以对中的硬编码1应用相同的操作 __str__ accountType 在里面 __init__ :

    self.accountType = AccountType(accountType)
    

    self.d self.accountType ,我建议不要在初始化时首先使用整数值:

    test = BankAccount("Max", AccountType.SAVINGS)
    

    这比使用幻数要清楚得多。更新到 将同时接受枚举及其值。