yieldPython中关键字的用途是什么?它有什么作用?
例如,我试图理解这段代码1:
def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
Run Code Online (Sandbox Code Playgroud)
这是来电者:
result, candidates = [], [self]
while candidates:
node = candidates.pop()
distance = node._get_dist(obj)
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
Run Code Online (Sandbox Code Playgroud)
_get_child_candidates调用该方法时会发生什么?列表是否返回?单个元素?它又被召唤了吗?后续通话何时停止?
1.代码来自Jochen Schulz(jrschulz),他为度量空间创建了一个很棒的Python库.这是完整源代码的链接:模块mspace.
我的代码应该读取4个字节但有时只读3个:
f = open('test.sgy', 'r+')
f.seek(99716)
AAA = f.read(4)
BBB = f.read(4)
CCC = f.read(4)
print len(AAA)
print len(BBB)
print len(CCC)
exit()
Run Code Online (Sandbox Code Playgroud)
并且该程序返回:4 3 4
我究竟做错了什么?谢谢!
我最近遇到了以下代码示例,用于使用带有SHA-256 HMAC的AES-256 CBC加密文件进行身份验证和验证:
aes_key, hmac_key = self.keys
# create a PKCS#7 pad to get us to `len(data) % 16 == 0`
pad_length = 16 - len(data) % 16
data = data + (pad_length * chr(pad_length))
# get IV
iv = os.urandom(16)
# create cipher
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
data = iv + cipher.encrypt(data)
sig = hmac.new(hmac_key, data, hashlib.sha256).digest()
# return the encrypted data (iv, followed by encrypted data, followed by hmac sig):
return data + sig
Run Code Online (Sandbox Code Playgroud)
因为在我的情况下,我加密的不仅仅是一个字符串,而是一个相当大的文件,我修改了代码来执行以下操作: …
python ×3
aes ×1
coroutine ×1
encryption ×1
generator ×1
hmac ×1
iterator ×1
pycrypto ×1
python-2.7 ×1
yield ×1