python - 如何延迟在 __init__ 中传递的 python 表达式的求值

标签 python

我有一个场景,我想在传递给另一个类的 init 的类之间使用逻辑运算符。但是,我想推迟对运算符的评估以调用基本上在 __call__ 内的对象。在那里,我想传递逻辑运算符所需的更多参数。

基本上,我想实现这个接口(interface):

IsAllowed(classes=[Auth1('some_value') | Auth2('some_other_value')]

但是,我想推迟对 classes=[Auth1('some_value') | 的评估Auth2('some_other_value') 到在 IsAllowed 上调用 __call__ 的时间,并传递一些在逻辑操作中使用的额外参数。

这就是 Auth 类在底层的样子:

class Auth:

    def __or__(self, other):
        return self.has_perm(run_time_arg) or other.has_perm(run_time_arg)

有办法实现吗?

最佳答案

如果您想允许延迟执行(稍后提供 some_value),请重新安排 API 以让您的调用者传递 lambda:

IsAllowed(classesFn = lambda value: [Auth1(value) | Auth2(value)])

...然后让被调用者调用该函数以获取它返回的值。


这可能看起来像:

class IsAllowed(object):
    def __init__(self, classesFn=None):
        self.classesFn = classesFn
    def __call__(self, value):
        classes = self.classesFn(value)
        # do logic using 'classes' here

关于python - 如何延迟在 __init__ 中传递的 python 表达式的求值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72911089/

相关文章:

python - 如何查找 **options 参数是什么?

python - 多环境coremltools安装

python - 如何计算数据帧中一行中非 NaN 列的数量?

python - 匹配冒号前后的短语

Python 等效 R 代码 - 从纪元到 POSIXlt 的数字秒

python - WXPython 中各个小部件的不透明度

python - 如何处理 IncompleteRead : in python

python - 如何替换对象特征内数字之间的文本

python - Django 多选字段 : Make some choices readonly when editing

python - 为什么我通过shell可以连接MySQL,但通过Python却无法连接?