在Python上运行语法错误

2024-09-30 01:29:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着遵循JS中的区块链教程,但我正在Python上尝试。你知道吗

我已经走了这么远,当我试图测试运行它,我得到了这个语法错误,这是困惑我,因为它似乎是合法的。你知道吗

有什么想法吗?你知道吗

import hashlib

class block:

def __init__(self, index, timestamp, data, previous= ''):
    self.index = index
    self.timestamp = timestamp
    self.data= data
    self.previous = previous
    self.hash = ''

def calculateHash(self):
    return hashlib.sha256(self.index + self.previous + self.timestamp+ (self.data).__str__()

class blockchain:
#btw this it where it says the error is: "class"
def __init__(self):
    self.chain= [self.createGenesisBlock()]

def createGenesisBlock(self):
    return block(0, "01/01/2017", "Genesis Block", "0")

def getLatestBlock(self):
    return self.chain[len(self.chain)-1]

def addBlock(self, newBlock):
    newBlock.previous = self.getLatestBlock().hash
    newBlock.hash= newBlock.calculateHash()
    self.chain.push(newBlock)

korCoin  = blockchain()
korCoin.addBlock(block(1, "10/07/2017", 4))
korCoin.addBlock(block(2, "12/07/2017", 40))

if __name__ = "__main__":
print(korCoin)

Tags: selfchaindataindexreturndefhashblock
2条回答

你的类中的函数都有错误的缩进。试试这个-

import hashlib

class Block:

    def __init__(self, index, timestamp, data, previous= ''):
        self.index = index
        self.timestamp = timestamp
        self.data= data
        self.previous = previous
        self.hash = ''

    def calculateHash(self):
        return hashlib.sha256(self.index + self.previous + self.timestamp+ (self.data).__str__()

class BlockChain:
    def __init__(self):
        self.chain= [self.createGenesisBlock()]

    def createGenesisBlock(self):
        return block(0, "01/01/2017", "Genesis Block", "0")

    def getLatestBlock(self):
        return self.chain[len(self.chain)-1]

    def addBlock(self, newBlock):
        newBlock.previous = self.getLatestBlock().hash
        newBlock.hash= newBlock.calculateHash()
        self.chain.push(newBlock)

korCoin = BlockChain()
korCoin.addBlock(block(1, "10/07/2017", 4))
korCoin.addBlock(block(2, "12/07/2017", 40))

if __name__ == "__main__":
    print(korCoin)

遵循python的缩进here

缺少右括号:

hashlib.sha256(self.index + self.previous + self.timestamp+ (self.data).__str__()hashlib.sha256(self.index + self.previous + self.timestamp+ (self.data).__str__())

我假设你已经正确地缩进了你的实际代码,但是在操作中粘贴了错误的标识。这就是为什么第一个答案要求你修正缩进。你知道吗

代码还有其他问题

  • self.index是一个整数,必须先将其转换为字符串,然后才能与其他字符串连接。不能将字符串和整数连接起来

  • self.previous是空字符串('') in the firstkorCoin.addBlock文件`但在第二个调用中是哈希对象。在与其他字符串连接之前,必须将其转换为字符串或检索其字符串表示形式

  • self.chain是一个列表,列表没有push方法。我想你是说append

相关问题 更多 >

    热门问题