Python 带有初始化 class 变量的 AttributeError

Python AttributeError with initialised class variable

我最近一直在 Python 中构建区块链。在我的 Block class 中,我初始化了一个 nonce 变量,稍后在 class 中使用它。但是,当我尝试在 class 中的其他地方使用该变量时,我得到 AttributeError: 'Block' object has no attribute 'nonce'。这是我的代码:

from hashlib import sha256


class Block():
    def __init__(self, data=None):
        self.timestamp = str(time.time())
        self.data = data
        self.previousHash = '0'*64
        self.hash = self.calculateHash()
        self.nonce = 0

        self.dict = {
            "Previous hash": self.previousHash,
            "Hash": self.hash,
            "Timestamp": self.timestamp,
            "Data": self.data
        }

    def mineBlock(self, difficulty):
        while self.hash[:difficulty] != '0'*difficulty:
            self.nonce += 1
            self.calculateHash()

        print('Block mined: ' + self.hash)

    def calculateHash(self):
        hashingText = f'{self.timestamp}{self.data}{self.previousHash}{self.nonce}'.encode(
            'utf-8')

        return sha256(hashingText).hexdigest()

这是错误的最后一部分,以防有帮助:

File "/Users/[MYNAME]/Developer/DigiGov/src/BlockClass.py", line 28, in calculateHash
    hashingText = f'{self.timestamp}{self.data}{self.previousHash}{self.nonce}'.encode(
AttributeError: 'Block' object has no attribute 'nonce'

在你做的__init__方法中

        self.hash = self.calculateHash()

在你做之前:

        self.nonce = 0

calculateHash() 取决于 nonce,但尚未设置。调换这些语句的顺序。