如何解决理解python语法——变量后跟括号
我在比特币的 Python 实现中看到了这种语法。
https://github.com/samrushing/caesure/blob/master/caesure/bitcoin.py
我以前从未见过这种语法,有人可以向我解释一下,或者在文档中我可以理解的地方给我看吗?
def dump (self,fout=sys.stdout):
D = fout.write
D ('hash: %s\n' % (hexify (dhash (self.render())),))
D ('inputs: %d\n' % (len(self.inputs)))
for i in range (len (self.inputs)):
(outpoint,index),script,sequence = self.inputs[i]
try:
redeem = pprint_script (parse_script (script))
except ScriptError:
redeem = script.encode ('hex')
D ('%3d %064x:%d %r %d\n' % (i,outpoint,index,redeem,sequence))
D ('outputs: %d\n' % (len(self.outputs),))
for i in range (len (self.outputs)):
value,pk_script = self.outputs[i]
pk_script = pprint_script (parse_script (pk_script))
D ('%3d %s %r\n' % (i,bcrepr (value),pk_script))
D ('lock_time: %s\n' % (self.lock_time,))
我说的是 D ('hash: %s\n' % (hexify (dhash (self.render())),))
解决方法
在 Python 中,您可以将函数分配给变量。
fout.write
是一个函数,因此在本例中,D
被分配给该函数。
D = fout.write
在这一行
D ('hash: %s\n' % (hexify (dhash (self.render())),))
,您正在调用函数D
,即fout.write
。这将是相同的:
fout.write('hash: %s\n' % (hexify (dhash (self.render())),))
您可以拥有一个具有函数类型的变量。
也许这个其他例子更容易理解:
foo = print
foo("Hello") # This prints Hello in the terminal
你可以看到这种变量有一个特殊的类:
>>> type(foo)
<class 'builtin_function_or_method'>
您定义的函数也会发生同样的情况:
def hello(s):
print(s)
hello("123") # prints 123
bar = hello
bar("123") # prints 123
在这种情况下,类类型不同:
>>> type(bar)
<class 'function'>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。