Fire (1) Fire 的傳入參數

Fire() 可以接受的參數型別有很多 e.g. function, dict, object and class。 下面是一些官網舉的例子。

1. 從多個函式中選擇:

我們可以定義多個函式並於執行的時候選擇特定函式。

import fire

def add(x, y):
  return x + y

def power(x, y):
  return x ** y

if __name__ == "__main__":
    fire.Fire()
$ python3 f.py power 10 3

1000

2. 封裝函式:

我們可以透過 dict 限制能夠被呼叫的函式。

import fire

def add(x, y):
  return x + y

def multiply(x, y):
  return x * y

def power(x, y):
  return x ** y

if __name__ == "__main__":
    fire.Fire({
        "add": add, 
        "multiply": multiply
    })

3. Fire 和 class:

我們可以透過物件方式傳遞給 Fire()。

import fire

class Calculator(object):
    def add(self, x, y):
        return x + y

    def multiply(self, x, y):
        return x * y

    def power(self, x, y):
        return x ** y

if __name__ == "__main__":
    calculator = Calculator()
    fire.Fire(calculator)

上面的例子等同於直接把類別傳進去。

import fire

class Calculator(object):
    def add(self, x, y):
        return x + y

    def multiply(self, x, y):
        return x * y

    def power(self, x, y):
        return x ** y

if __name__ == "__main__":
    fire.Fire(Calculator)

你可能會覺得 class 被傳入不如 object 被傳入來得自由, 通常 object 會呼叫特定的 constructor 使其運作行為有所不同。但其實我們傳入 class 時也可以呼叫特定的 constructor:

import fire

class BrokenCalculator(object):

    def __init__(self, offset=1):
        self._offset = offset

    def add(self, x, y):
        return x + y + self._offset

    def multiply(self, x, y):
        return x * y + self._offset

    def power(self, x, y):
        return x ** y


if __name__ == '__main__':
  fire.Fire(BrokenCalculator)
$ python3 f.py add 10 20 --offset 0 #  屬於 constructor 的參數

Reference:

[1] https://github.com/google/python-fire

[2] https://github.com/google/python-fire/blob/master/docs/guide.md


留言

熱門文章