You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.6报NameError: name '' is not defined,区块链代码故障排查求助

排查并修复区块链代码中的NameError问题

嘿,我帮你看了下这段区块链代码,出现Python 3.6的NameError其实是因为几个很容易犯的拼写错误,咱们一步步来定位和解决:

错误定位

从你提供的代码片段里能看到两个直接导致错误的问题:

  • 类方法参数拼写错误:proof_of_work方法的第一个参数写成了slef,Python类的实例方法必须以self作为第一个参数,拼写错误会让解释器找不到这个变量,直接抛出NameError。
  • 循环内变量截断/拼写错误:代码里的while se...明显是未写完或者拼写失误,这里的截断导致了未定义的变量名,也是触发NameError的原因之一。

另外,原代码里调用了new_block方法但没有定义它,这也是后续运行会报错的潜在问题,我一起帮你补上了。

修复后的完整代码

import hashlib
import json
from time import time

class Blockchain(object):
    def __init__(self):
        self.chain = []
        self.current_transactions = []
        # Create the genesis block
        self.new_block(previous_hash=1, proof=100)
    
    def new_block(self, proof, previous_hash=None):
        """生成新块并添加到链中"""
        block = {
            'index': len(self.chain) + 1,
            'timestamp': time(),
            'transactions': self.current_transactions,
            'proof': proof,
            'previous_hash': previous_hash or self.hash(self.chain[-1]),
        }
        # 重置当前交易列表
        self.current_transactions = []
        self.chain.append(block)
        return block
    
    def new_transaction(self, sender, recipient, amount):
        """添加新交易到待处理交易列表"""
        self.current_transactions.append({
            'sender': sender,
            'recipient': recipient,
            'amount': amount,
        })
        # 返回该交易将被包含的块的索引
        return self.last_block['index'] + 1
    
    @staticmethod
    def hash(block):
        """生成块的SHA-256哈希值"""
        # 确保字典排序一致,否则哈希值会不同
        block_string = json.dumps(block, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()
    
    @property
    def last_block(self):
        """返回链中最后一个块"""
        return self.chain[-1]
    
    def proof_of_work(self, last_proof):
        """
        Simple proof of Work Algorithm:
        - Find a number p' such that hash(pp') contains leading 4 zeros, where p is the previous p'
        - p is the previous proof, and p'is the new proof
        :param last_proof: <int>
        :return: <int>
        """
        proof = 0
        # 修复拼写错误,实现完整的工作量证明逻辑
        while self.valid_proof(last_proof, proof) is False:
            proof += 1
        return proof
    
    @staticmethod
    def valid_proof(last_proof, proof):
        """验证工作量证明:hash(last_proof, proof)是否以4个0开头"""
        guess = f'{last_proof}{proof}'.encode()
        guess_hash = hashlib.sha256(guess).hexdigest()
        return guess_hash[:4] == "0000"

关键修复说明

  1. 修正了proof_of_work方法的参数拼写:把slef改为self,符合Python类方法的规范;
  2. 补全了while循环的逻辑:替换掉截断的se...,用self.valid_proof来判断工作量证明是否符合要求;
  3. 补充了区块链核心方法:新增了new_block、new_transaction、hash和valid_proof方法,让代码能完整实现区块链的基础功能。

现在你可以运行这段修复后的代码,NameError应该就不会再出现了。

内容的提问来源于stack exchange,提问作者xAssasinSoulx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:27:36