我试着遵循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)
你的类中的函数都有错误的缩进。试试这个-
遵循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 first
korCoin.addBlock文件`但在第二个调用中是哈希对象。在与其他字符串连接之前,必须将其转换为字符串或检索其字符串表示形式self.chain
是一个列表,列表没有push
方法。我想你是说append
相关问题 更多 >
编程相关推荐