Smart Contract 開發實戰(四) — 物件的繼承與使用

Bryan Yang
A multi hyphen life
3 min readJul 16, 2018

這一系列主要紀錄學習開發 Smart Contract 的過程…

繼承

Solidity 除了 function 之外,當然也有物件以及繼承.contract 就是像 python 的 class 一樣,可以宣告一個物件:

contract People{
function greeting() public returns (string) {
return "Hi";
}
}

既然有物件就可以繼承

contract Baby is People{
function cry() public returns (string) {
return "QQ";
}
}

Baby 可以使用 People 裡面 public 或是 internal 的函式.

使用其他 solidity 檔案

如果要使用其他的 .sol 檔中的物件,可以跟python 一樣使用 import.但 solidity 的 import 是 import 整個 .sol 檔案路徑.

import "./someothercontract.sol";

使用其他的 Contract

如果想要直接呼叫其他 Contract (別忘了所有 smart contract 都部署在以太坊上),就必須制定介面(interface).

contract Baby is People{
mapping(address => bytes32) names;

function setName(bytes32 _name) public {
numbers[msg.sender] = _name;
}
function getName(address _myAddress) public view returns (uint) {
return names[_myAddress];
}
}

這是一個簡單的 Contract ,直接呼叫會根據呼叫的 address 對到一個名字,而後透過 getName 來查詢名字.如果其他的 Contract 要呼叫這個就得加上 interface.

contract Baby is People{
mapping(address => bytes32) names;

function setName(bytes32 _name) public {
numbers[msg.sender] = _name;
}
function getName(address _myAddress) public view returns (uint) {
return names[_myAddress];
}
}
contract NameInterface {
function getName(address _myAddress) public view returns (uint);
}

最後那三行就是getName 的 Interface.看起來跟原本的 getName 很像.但是有兩點不同:

  • 在這個 Interface 裡面,只有 getName 一項 Function,沒有其他東西.
  • 這個 function 不需要內容,亦即沒有定義 {}.

更多使用請靜待下集…

--

--

Bryan Yang
A multi hyphen life

Data Engineer, Data Producer Manager, Data Solution Architect