ethereum - 为什么需要括号来访问 python 中的 Solidity 合约变量?

标签 ethereum solidity web3py

在 Solidity 合约中,有如下声明:

contract Lottery is VRFConsumerBase, Ownable {
address payable[] public players;
...
...

在同一契约(Contract)的其他地方,有一个分配如下:

....
....
recentWinner = players[someIndex];
....
....

} 

deploy.py Python脚本用于部署合约。部署合约的函数是:

def deploy_lottery():
      Lottery.deploy(....)
....
....

部署并执行其他操作后...可以使用括号从 python 脚本访问合约的 recentWinner 变量,如下所示:

def end_lottery():
      print(f"{lottery.recentWinner()} is the winner!")
  

我相当基本的问题是,为什么使用括号? centreWinner 不是 Lottery 合约中定义的函数。如果我运行不带括号的脚本,我会得到以下输出。

<ContractCall 'recentWinner()'> is the winner!
Terminating local RPC client...

所以看来括号是必要的。有人可以解释一下发生了什么事吗?为什么我应该像函数一样对待这个变量来检索它的值?如果您还可以向我指出一些相关的帖子/阅读 Material ,我将不胜感激。谢谢!

最佳答案

EVM 没有公共(public)变量,只有公共(public)访问器函数。

在幕后,Solidity 编译器会为您生成一个名为 recentWinner() 的函数。 This is called accessor or getter function 。与 Java 等语言不同,该函数没有 get 前缀。

关于ethereum - 为什么需要括号来访问 python 中的 Solidity 合约变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70887688/

相关文章:

python - 解析器错误 : Source file requires different compiler version

ethereum - 获取/猜测未验证合约的外部方法

transactions - 我应该在以太坊上有多少个确认?

javascript - 如何使用 --constructor-args 参数运行 Hardhat?

javascript - web3 websocket连接阻止节点进程退出

django - 使用 web3.py 交易永远不会被挖掘

javascript - Web3 1.1.0 的问题

node.js - 类型错误 : Explicit type conversion not allowed from "int_const -1" to "uint256"

python - 如何修复 web3 模块 AttributeError?

ethereum - 使用 w3.eth.contract() 部署智能合约时出错 : "The method eth_sendTransaction is not supported"