我的实例没有在我的while循环中更新[重复]

问题描述 投票:-2回答:2

这个问题在这里已有答案:

我想通过将nonce更改为1来重新计算哈希值,但self.hash的实例不会更改。

我不是那么有经验,也不知道如何解决这些类型的问题

import hashlib

class Block:

  def __init__(self, timestamp, transaction, previousHash = ''):
    self.timestamp = timestamp
    self.transaction = transaction
    self.nonce = 0
    self.previousHash = previousHash
    self.hash = self.calculateHash()

  def mineBlock(self):
    checkIfTrue = str(self.hash).startswith('0')
    while checkIfTrue != True:
        self.nonce += 1
        self.hash = self.calculateHash()
        print(self.hash)

    print("block mined")

  def calculateHash(self):
    h = hashlib.sha256((str(self.timestamp) + str(self.transaction) + str(self.previousHash) + str(self.nonce)).encode('utf-8'))
    return h.hexdigest()
python
2个回答
0
投票

我尝试了你的代码,它适用于我,self.hash更改。但程序陷入无限循环,因为条件“while checkIfTrue!= True:”在循环内部不会改变。更新self.hash后,您需要退出循环并再次执行“checkIfTrue = str(self.hash).startswith('0')”。


0
投票

你没有在循环中更新checkIfTrue

没有真正需要该变量,只需将哈希检查放在while语句中即可。

while not str(self.hash).startswith('0'):
    self.nonce += 1
    self.hash = self.calculateHash()
    print(self.hash)
© www.soinside.com 2019 - 2024. All rights reserved.