首页 > 解决方案 > 从python中的另一个类动态调用类和类属性

问题描述

我正在构建一组类,以帮助更好地管理围绕每个角色的复杂业务逻辑以及该角色中的操作。每个角色都是一个类,其中包含定义操作的方法。我遇到的问题是,在动态定位类和类方法时,如果我在同一个对象中调用类方法两次,我会从第一次调用中得到原始结果。

ManageDistrict 和 ManageOperations 继承自的 ActionBase 类是一个抽象类。不认为我遇到的问题需要它。

class Roles(object):
    def __init__(self, roles, action):
        self.roles = roles
        self.action = action
        self.role_class = self._get_role_class()
        self.actions_that_can_be_performed = []

    def _get_role_class(self):
        classes = ["ManageDistrict", "ManageOperations"]
        _role_object = []
        for role in self.roles:
            class_role = None
            for cls in classes:
                class_role = getattr(eval(cls), "class_role")

                if role == class_role:
                    _role_object.append(cls)
        return _role_object

    def perform_action(self, **kwargs) -> bool:
        """determine if user can perform the correct actions

        Returns:
            bool: [description]
        """
        for cls in self.role_class:
            try:
                method = getattr(eval(cls), self.action)
                return method(**kwargs)

            except IDMRolesException as e:
                return False


class ManageDistrict(ActionBase):
    class_role = "ACTION_MANAGE_DISTRICT"

    def __init__(self):
        super().__init__()


    @classmethod
    def post_dispute(cls, **kwargs):
        return kwargs['bool_val']


class ManageOperations(ActionBase):
    class_role = "ACTION_MANAGE_OPERATIONS"

    def __init__(self):
        super().__init__()

    @classmethod
    def post_dispute(cls, **kwargs):
        return kwargs['bool_val']

######################################################################################

role = Roles(roles=['ACTION_MANAGE_OPERATIONS'], action='post_dispute')

if role.perform_action(bool_val=True):
    print('this is true')

if role.perform_action(bool_val=False):
    print('this still returns true on the 2nd call')

标签: pythondynamicsubclassuser-roles

解决方案


推荐阅读