python - 从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')
解决方案
推荐阅读
- android - 如何访问android主项目中模块Jar的类文件
- node.js - 用额外数据等待 Promise.all 的好的设计模式是什么
- windows - Windows 桌面图标位置存储在哪里?
- c# - 在 C# 中将字符串转换为 json 格式。Newtonsoft.json 显示黄色标记
- go - 检查所有字段是否在结构初始化中显式设置的 Linter
- angular - 如何在角度插值标记中使用字符串函数
- flutter - 颤动,如何在图像底部放置按钮?
- corda - Corda 是否支持状态删除场景?
- amazon-web-services - 如何通过对资源进行手动更改来更新 terraform 状态
- haskell - 使用 foldl 的 Haskell 函数组合