簡體   English   中英

Python:調用模塊時移交變量

[英]Python: Handover a variable while calling a module

在 python 中,我想調用一個自建模塊並將其交給某個變量(例如 integer 編號)。 通過這個,我想指定從哪個文件調用模塊,即當我從文件 A 導入模塊 XY 時,模塊將在某種模式下工作(由變量指定),如果我從文件導入模塊 XY B、模塊工作在其他模式

我的第一個想法是通過定義函數來做到這一點; 但是當我的模塊中有很多功能時,我必須在每個 function 中單獨添加這個額外的變量。

導入模塊時是否有更優雅的方法來為模塊分配某個變量/操作模式

import mymodule # here, I'd like to hand-over a global variable to "mymodule" which can be used in the source-code of "mymodule"

mymodule.any_function_from_it()

模塊“mymodule”可能具有以下結構:

def any_function_from_it_independent_from_global_variable():
   print("x")
   # more code to follow here

if variable_handed_over==0:
   def any_function_from_it():
      print("xy")
      # more code to follow here

else:
   def any_function_from_it():
      print("xyz")
      # more code to follow here


有幾十種不同的方法可以實現您似乎想要的一般最終結果 - 但“在導入時根據“傳遞的變量”的值配置模塊以不同的行為”不是其中之一。

這是一個模塊,顯示了兩種常見的方法來做你所描述的事情。 第一種方法,使用 class ThingDoer是一種面向對象的方法。 第二種方法,使用 function get_thing_doer是一種功能方法。

模塊: doers.py

class ThingDoer(object):
    def __init__(self, is_special_mode=False):
        self._is_special_mode = is_special_mode


    def _special_mode_do_it(self):
        print("I'm special!")

    def _do_it(self):
        print("I'm not special, but please accept me anyway")

    def do_the_thing(self):
        if self._is_special_mode:
            self._special_mode_do_it()
            return

        self._do_it()



def get_thing_doer(is_special_mode=False):
    def special_mode_do_it():
        print("I'm special")

    def do_it():
        print("I'm not special, but please accept me anyway")

    if is_special_mode:
        return special_mode_do_it

    return do_it

您可以通過在同一目錄中創建另一個模塊來了解其工作原理。

模塊: do_it.py

from doers import get_thing_doer, ThingDoer


if __name__ == '__main__':
    foo = ThingDoer()  # is_special_mode argument takes default value of False
    foo.do_the_thing()  # prints: "I'm not special, but please love me anyway!"

    bar = ThingDoer(is_special_mode=True)
    bar.do_the_thing()  # prints: "I'm Special!"

    bazz = get_thing_doer()  # is_special_mode argument takes default value of False
    bazz()  # prints: "I'm not special, but please love me anyway!"

    buzz = get_thing_doer(is_special_mode=True)
    buzz()  # prints "I'm special!"

然后,從命令行運行: python do_it.py

更抽象地說:在 python 中,條件行為通常不在導入時基於狀態配置進行管理。

相反,條件行為(基於配置或其他應用程序狀態)作為程序執行流程的一部分發生。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM