我正在训练我的设计模式的技能.使用Factory模式,我试图从一个有限的列表中获取并弹出示例编号.

在初始化seccond帐户时,我收到了IndexError.在调试过程中,我注意到在对acc01 and acc02进行初始化期间,我使用了4次Account Manager.number()函数.与Account Manager er.count_id()相同.

from abc import ABC
from random import choice, randint


class AccountsManager:
    def __init__(self) -> None:
        self._last_id_number = 0
        self._allowed_numbers = [randint(10_000, 99_999) for _ in range(5)]

    @property
    def number(self) -> int:
        if not self._allowed_numbers:
            raise IndexError
        number = choice(self._allowed_numbers)
        self._allowed_numbers.pop(self._allowed_numbers.index(number))
        return number

    @property
    def account_id(self) -> int:
        account_id = self._last_id_number
        self._last_id_number += 1
        return account_id


class TemplateBankAccount(ABC):
    def __init__(self, manager, owner: str, account_type: str = '') -> None:
        self.manager = manager
        self.id_number = manager.account_id
        self.account_number = manager.number

        self.owner = owner
        self.account_type = account_type
        self._amount = 0

    def __str__(self) -> None:
        raise NotImplementedError

    @property
    def amount(self) -> int:
        return self._amount

    @amount.setter
    def amount(self, direction: str, value: int) -> None:
        if direction == '+':
            self._amount += value
        elif direction == '-':
            self._amount -= value
        else:
            raise ValueError


class PersonalBankAccount(TemplateBankAccount):
    def __init__(self, manager, owner) -> None:
        super().__init__(manager, owner, account_type='Personal Account')

    def __str__(self) -> str:
        return f'{self.account_type}: {self.owner}'


class CompanyBankAccount(TemplateBankAccount):
    def __init__(self, manager, owner) -> None:
        super().__init__(manager, owner, account_type='Company Account')

    def __str__(self) -> str:
        return f'{self.account_type}: owner name restricted.'


class SavingsBankAccount(TemplateBankAccount):
    def __init__(self, manager, owner) -> None:
        super().__init__(manager, owner, account_type='Savings Account')

    def __str__(self) -> str:
        return f'{self.account_type}: {self.owner}'


class AccountCreator:
    def __init__(self) -> None:
        self.manager_group = AccountsManager()

    def create_account(self, owner_name, account_type):
        allowed_types = {'Personal': PersonalBankAccount(self.manager_group, owner_name),
                         'Company': CompanyBankAccount(self.manager_group, owner_name),
                         'Savings': SavingsBankAccount(self.manager_group, owner_name)}

        return allowed_types.get(account_type, 'Non offered account type')


def main() -> None:
    creator = AccountCreator()
    create_account = creator.create_account
    acc_01 = create_account('Andrew Wiggins', 'Personal')
    acc_02 = create_account('NASA Inc.', 'Company')
    acc_03 = create_account('John Paul Wieczorek', 'Savings')

    list_of_accounts = [str(account) for account in (acc_01, acc_02, acc_03)]
    print('\n'.join(list_of_accounts))


if __name__ == '__main__':
    main()

我不知道如何更改代码以获取self._last_id_numberself._allowed_number之间的值 每create_account个呼叫只有一次.

推荐答案

问题是您的工厂方法(create_account)创建所有对象,而这并不是您想要做的事情--您只需要创建请求的对象.最简单的工厂是这样的:

    def create_account(self, owner_name, account_type):
        if account_type == "Personal":
            return PersonalBankAccount(self.manager_group, owner_name)

        if account_type == "Company":
            return CompanyBankAccount(self.manager_group, owner_name)

        if account_type == "Savings":
            return SavingsBankAccount(self.manager_group, owner_name)

        return "Non offered account type"

或者使用存储构造函数的dict:

    def create_account(self, owner_name, account_type):
        allowed_types = {
            "Personal": PersonalBankAccount,
            "Company": CompanyBankAccount,
            "Savings": SavingsBankAccount,
        }

        if account_type in allowed_types:
            return allowed_types.get(account_type)(self.manager_group, owner_name)

        return "Non offered account type"

Python相关问答推荐

更改Seaborn条形图中的x轴日期时间限制

如何修复使用turtle和tkinter制作的绘画应用程序的撤销功能

由于瓶颈,Python代码执行太慢-寻求性能优化

韦尔福德方差与Numpy方差不同

在Google Colab中设置Llama-2出现问题-加载判断点碎片时Cell-run失败

如何从具有不同len的列表字典中创建摘要表?

如何在WSL2中更新Python到最新版本(3.12.2)?

梯度下降:简化要素集的运行时间比原始要素集长

如何并行化/加速并行numba代码?

将scipy. sparse矩阵直接保存为常规txt文件

Python Pandas—时间序列—时间戳缺失时间精确在00:00

OpenCV轮廓.很难找到给定图像的所需轮廓

为什么调用函数的值和次数不同,递归在代码中是如何工作的?

计算空值

用fft计算指数复和代替求和来模拟衍射?

如何将泛型类类型与函数返回类型结合使用?

需要帮助使用Python中的Google的People API更新联系人的多个字段'

按条件添加小计列

为什么后跟inplace方法的`.rename(Columns={';b';:';b';},Copy=False)`没有更新原始数据帧?

如何提高Pandas DataFrame中随机列 Select 和分配的效率?