是否有可能做类似的事情
c = MyObj()
c.eval("func1(42)+func2(24)")
Run Code Online (Sandbox Code Playgroud)
在Python ..我有func1()和func2()在对象'c'的范围内进行评估(如果它们是该类定义中的成员函数)?我不能做一个简单的解析,因为对于我的应用程序,eval字符串可能变得任意复杂.我想用ast模块做一些魔法可能会有所作为,但是由于文学史上的d ,,我不知道在哪里看:
import ast
class MyTransformer(ast.NodeTransformer):
def visit_Name(self, node):
# do a generic_visit so that child nodes are processed
ast.NodeVisitor.generic_visit(self, node)
return ast.copy_location(
# do something magical with names that are functions, so that they become
# method calls to a Formula object
newnode,
node
)
class Formula(object):
def LEFT(self, s, n):
return s[:n]
def RIGHT(self, s, n):
return s[0-n:]
def CONCAT(self, *args, **kwargs):
return ''.join([arg for arg in args])
def main():
evalString = …Run Code Online (Sandbox Code Playgroud) 我遇到的问题的淡化版本就是这个.对于XML文件,例如:
<?xml version="1.0" encoding="UTF-8"?>
<items>
<item cols="1">Item 1</item>
<item cols="1">Item 2</item>
<item cols="1">Item 3</item>
<item cols="1">Item 4</item>
<item cols="1">Item 5</item>
<item cols="1">Item 6</item>
<item cols="1">Item 7</item>
<item cols="1">Item 8</item>
<item cols="1">Item 9</item>
<item cols="2">Item 10</item>
<item cols="1">Item 11</item>
<item cols="1">Item 12</item>
<item cols="1">Item 13</item>
<item cols="1">Item 14</item>
<item cols="1">Item 15</item>
<item cols="1">Item 16</item>
<item cols="1">Item 17</item>
<item cols="1">Item 18</item>
</items>
Run Code Online (Sandbox Code Playgroud)
我需要能够在单个列页面布局中打印'具有'cols = 1'的项目,以及在双列页面布局中打印'cols = 2'的项目.必须保留物品的顺序.具有相同@cols值的所有连续'项目需要显示为连续流.每次@cols值改变时,我都需要打破一个新页面并根据需要更改布局.
我正在做这样的事情:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
<fo:layout-master-set>
<fo:simple-page-master master-name="one-column-page-master">
<fo:region-body …Run Code Online (Sandbox Code Playgroud) 我试图理解Python字典必须在内部做什么才能找到密钥.在我看来,哈希将首先被评估,如果有冲突,Python将遍历键,直到找到一个eq返回True的那个.这让我想知道为什么以下代码有效(测试代码仅用于理解内部):
class MyClass(object):
def __eq__(self, other):
return False
def __hash__(self):
return 42
if __name__=='__main__':
o1 = MyClass()
o2 = MyClass()
d = {o1: 'o1', o2: 'o2'}
assert(o1 in d) # 1
assert(d[o1]=='o1') # 2
assert(o2 in d) # 3
assert(d[o2]=='o2') # 4
Run Code Online (Sandbox Code Playgroud)
字典不应该无法找到正确的密钥(在#2和#4情况下返回'o1'或'o2',或者抛出错误,具体取决于内部实现).在两种情况下,当它永远不能正确地"等同"键时(因为eq返回False),它如何能够在正确的键上着陆.
我在哈希上看到的所有文档总是提到哈希和eq,而不是cmp,ne等,这让我觉得这两个是唯一在这个场景中发挥作用的人.