- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我已经实现了用于延迟评估转储到 JSON 的配置的类。没问题,只需扩展编码器以使用特定协议(protocol)(固定方法/属性)主动评估类。
class DeferredCall(object):
"""Call that is evaluated lazyly"""
def __init__(self, func, *func_args, **func_kwargs):
self.func = func
self.func_args = func_args
self.func_kwargs = func_kwargs
def resolve(self): # called by JSON encoder
return self.func(*self.func_args, **self.func_kwargs)
a = DeferredCall(lambda: 1)
a # gives <[module].DeferredCall at 0x1e99410>
a.resolve() # gives 1
现在,随着强大的力量而来的是想要更多力量的用户。也就是说,直接对类进行操作而不是对它们所代表的值进行操作。根据python data model ,这应该像实现魔术方法一样简单,例如 __add__
、__len__
等
添加
def __add__(self, other):
return self.resolve() + other
或
def __add__(self, other):
return self.resolve().__add__(other)
会正确地给我 a + 3 == 4
。
不过,实现所有 魔术方法有点太多了。所以我尝试使用 __getattr__
def __getattr__(self, item):
return getattr(self.resolve(), item)
它适用于 a.__mul__(3) == 3
但对于 a * 3 == 3
和 TypeError: unsupported operand type(s ) 对于 *: 'DeferredCall' 和 'int'
。
那么有什么其他方法可以将运算符转发给包装值吗?理想情况下,无需冒险以编程方式编写代码或 __getattribute__
的麻烦。
最佳答案
发布我的解决方案以防其他人需要它。大多数“内置”操作(例如 *
或 len
)在设计上不会使用 __getattr[ibute]__
。
我已经决定以编程方式创建方法
class DeferredCall(object):
def __init__(self, func, *func_args, **func_kwargs):
self.func = func
self.func_args = func_args
self.func_kwargs = func_kwargs
def resolve(self):
return self.func(*self.func_args, **self.func_kwargs)
# magic must be resolved explicitly
# self other - resolve in reflected order to allow other to resolve as well
for so_magic in [("lt", "gt"), ("le", "ge"), ("eq", "eq"), ("ne", "ne"), ("add", "radd"), ("sub", "rsub"), ("mul", "rmul"), ("div", "rdiv"), ("truediv", "rtruediv"), ("floordiv", "rfloordiv"), ("mod", "rmod"), ("divmod", "rdivmod"), ("pow", "rpow"), ("lshift", "rlshift"), ("rshift", "rrshift"), ("and", "rand"), ("xor", "rxor"), ("or", "ror")]:
for func_name, refl_name in [(so_magic[0], so_magic[1]), (so_magic[1], so_magic[0])]:
exec("def __%(fname)s__(self, other):\n\ttry:\n\t\tres = other.__%(rname)s__(self.resolve())\n\t\tif res == NotImplemented:\n\t\t\traise AttributeError\n\texcept AttributeError:\n\t\tres = self.resolve().__%(fname)s__(other)\n\treturn res" % {"fname": func_name, "rname": refl_name})
# regular magic - immutable only
for magic in ("str", "nonzero", "unicode", "getattr", "call", "len", "getitem", "missing", "iter", "reversed", "contains", "getslice", "neg", "pos", "abs", "invert", "complex", "int", "long", "float", "oct", "hex", "index"):
exec("def __%(fname)s__(self, *args, **kwargs):\n\treturn self.resolve().__%(fname)s__(*args, **kwargs)" % {"fname": magic})
基本上,魔术方法必须分为两类:自包含的和上下文的。
自包含的是直接创建的,解析调用并执行魔术方法。例如,len
解析为:
def __len__(self, *args, **kwargs):
return self.resolve().__len__(*args, **kwargs)
上下文的必须反转调用,例如“大于”other
实际上检查 other
是否“小于”self
。如果两个对象都是延迟调用,则这是必需的,允许 other
也解析自己;否则,许多方法都会引发 TypeError
。仅当 other
没有反转版本时才使用直接求值。
def __gt__(self, other):
try:
res = other.__lt__(self.resolve())
if res == NotImplemented:
raise AttributeError
except AttributeError:
res = self.resolve().__gt__(other)
return res
一些调用可能可以更有效地实现,因为 python 使用了一些技巧(这正是我的问题首先出现的地方)。例如,乘法可以利用交换性:
def __mul__(self, other):
"""self * other"""
return other * self.resolve()
关于python - 惰性评估 : forward operations to deferred value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33393474/
目前,由于生成变量的评估,我的Makefile遇到了问题。我降低了复杂性,仅保留了导致问题的基本要素。 读取Makefile时, $(LIST)被评估为文件列表。 在步骤1中,其中一个文件被删除。 在
为什么这 eval 没有调用alert("Summer") ? eval('(caption="Summer";alert(caption))'); 和《夏天》里的台词有关系吗? 最佳答案 Uncau
我正在努力让以下工作正常进行。最初似乎可以工作,但不知何故它停止工作了 var setCommonAttr = "1_row1_common"; var val = document.getEleme
eval('({"suc":true})') 以上错误,应该是: eval('{"suc":true}') 为什么? 最佳答案 当尝试评估时,解释器会看到大括号并认为它是一个 block 开头。将其括
我的页面 A 发出了 ajax 调用并引入了片段 B。该片段被添加到 DOM 中,并且该片段中的所有脚本都经过了评估。在该代码片段中,我有 2 个脚本标签: function doOptions()
这里是javascript代码: var test = { "h" : function (a) {return a;}, "say" : "hello" }; 第一次运行: test
我正在查看一些工作代码,并遇到了这一行: eval("\$element = \"$element\";"); 我真的很困惑为什么任何 PHP 开发人员都会写这一行。除了给自己设置一个变量之外,这还有
谁能帮我解决以下问题: 我有这样的代码: if(cond1 && cond2 && .. && cond10) 这里,cond1 是昂贵的操作,其输出是 boolean 值。 现在我的问题是,当 co
**摘要:**华为AppCube应用魔方顺利通过信通院评估,被认证为具备 “低代码开发平台通用能力”的企业服务平台。 本文分享自华为云社区《华为AppCube通过中国信通院“低代码开发平台通用能力要求
我正在尝试通过 PHP 从图像的 EXIF 数据中获取焦距。 这是我目前得到的代码: $exif = exif_read_data("$photo"); $length10 = $exif['Foca
我想使用id =“key”将一个类添加到元素中,但是为什么不起作用?我是js的初学者:这是代码: audio.classList.add('yellow'); 这是错误: null is not an
这是我的 XML: QueWay Password Recovery 现在我想用 php 用 xpath 选择文本“QueWay”。到目前为止我所拥有的一切都很好: $xml =
使用下面的代码,即使我输入的数字大于 18,我也会得到这个结果。 运行:你今年多大? 21你还没有达到成年年龄!构建成功(总时间:3 秒) 我是java新手,正在尝试自学,有人可以帮忙吗? impor
我正在阅读 http://www.cran.r-project.org/doc/manuals/R-lang.pdf手册第 4.3 章,我就是不明白。也许有人可以给我一个快速的解释,为什么 R 的行为
在这个实现中,每次都会评估 hand 并返回另一个列表吗? foreach (Card card in hand.Cards) { } 我们应该用下面的实现替换上面的实现吗? var cards =
我正在制作 LINQ lambda 表达式: Expression> add = (x, y) => x + y; 但现在我将如何评估它,比如说找到 2+3? 最佳答案 这应该适合你: var su
我正在制作一个语言解释器,我已经到了需要评估 if 语句的地步。起初我认为这很简单,我能够让我的解释器评估简单的 if 条件,10 == 10 但是当我试图让它评估更复杂的条件时, 10 == 10
我正在尝试以下代码,该代码向 RDD 中的每一行添加一个数字,并使用 PySpark 返回 RDD 列表。 from pyspark.context import SparkContext file
在阅读了很多关于 Lisp eval-when 运算符的文档后,我仍然无法理解它的用途,我知道使用这个运算符我可以控制表达式的计算时间,但我做不到找出任何可能适用的示例? 最好的问候,utxee. 最
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于 Stack Overflow 来说是偏离主题的,
我是一名优秀的程序员,十分优秀!