gpt4 book ai didi

python - 如何在实例化之前更改 __init__ 参数

转载 作者:行者123 更新时间:2023-12-05 05:38:24 25 4
gpt4 key购买 nike

我想实现这样一个简单的界面:

IsAllowed(perms=[IsAdmin(runtime_value) | HasPerm('*')])

由于一些变量在实例化时不可用,我不得不推迟对 perms=[IsAdmin() | 的评估HasPerm('*')] 到稍后的时间点(当 __call__ 被我正在使用的 FastAPI 网络框架调用 IsAllowed 时)。我最接近实现的是以下内容:

IsAllowed(perms = lambda runtime_value: [IsAdmin(runtime_value) | HasPerm('*')])


class IsAllowed(object):
def __init__(self, perms=None):
self.perms = perms
def __call__(self, runtime_value):
result = self.perms(runtime_value)
return result

不,我的问题是,有什么方法可以使接口(interface)保持为 IsAllowed(perms=[IsAdmin(runtime_value) | HasPerm('*')]) 但是,以某种方式注入(inject) lambda 在实例化之前进入它?

我在考虑元类或利用 __init_subclass__ Hook ?有什么想法吗?

最佳答案

如果我正确理解你的问题,你想要这样的东西:

from typing import Any


class IsAllowed(object):
def __init__(self, *perms):
self.perms = perms


def __call__(self, args: list[Any]):
return all(self.perms[i](args[i]) for i in range(len(args)))

checker = IsAllowed(IsAdmin, HasPerm)
checker(“somevalue”, “*”)

更新:

对于评论区提到的案例:

from typing import Any, Callable


class Operation:
pass


class Or(Operation):
def __init__(self, *funcs: Callable[[Any], bool]) -> None:
self.funcs = funcs

def __call__(self, val: Any) -> bool:
return any(func(val) for func in self.funcs)

def __or__(self, other: Operation) -> Operation:
return Or(*self.funcs, other.func)


class Predicate:
def __init__(self, func: Callable[[Any], bool]) -> None:
self.func = func

def __or__(self, other) -> Or:
return Or(self.func, other.func)


def Is1(x: int) -> bool:
return x == 1


def Is2(x: int) -> bool:
return x == 2


def Is3(x: int) -> bool:
return x == 3


def main() -> None:
pred1 = Predicate(Is1)
pred2 = Predicate(Is2)
pred3 = Predicate(Is3)

fancy_pred = pred1 | pred2 | pred3

for i in range(5):
print(fancy_pred(i))


if __name__ == "__main__":
main()

关于python - 如何在实例化之前更改 __init__ 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72920385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com