0

功能我有一個程序,定義函數verboseprint到打印或不打印基於一個布爾屏幕:功能定義在Python

# define verboseprint based on whether we're running in verbose mode or not 
if in_verbose_mode: 
    def verboseprint (*args): 
     for arg in args: 
      print arg, 
     print 
    print "Done defining verbose print." 
else: 
    # if we're not in verbosemode, do nothing 
    verboseprint = lambda *a: None 

我的程序使用多個文件,而且我喜歡在所有這些中使用verboseprint的定義。所有的文件將通過in_verbose_mode布爾值。我知道我可以在文件中自己定義verboseprint,然後將其導入到我的所有其他文件中,但是我需要函數定義能夠基於布爾值聲明兩種不同的方式。

總之:我需要一個函數,可以用兩種不同的方式聲明另一個函數,然後我可以導入到多個文件中。

任何幫助,將不勝感激。

+0

要聲明一個功能,以不同的方式使用它無處不在,這是多態是如何工作的:http://stackoverflow.com/questions/1031273/what-is-polymorphism-what-is-it-換和如何 - 是 - 它使用。通常,你不通過這種方式在python中定義一個函數。 –

+0

我不明白你的意思是「所有的文件都會通過'in_verbose_mode'布爾值。」你的意思是每個文件都有自己的變量嗎? –

回答

3

通常你不想用這種方式定義一個函數。

而且我覺得最簡單的方式來實現,這是你傳遞布爾作爲函數參數,並定義基於參數的行爲:

def verboseprint (*args, mode): 
    if mode == in_verbose_mode: 
     for arg in args: 
      print arg, 
     print 
     print "Done defining verbose print." 
    # if we're not in verbosemode, do nothing 
    ##else: 
    ## verboseprint = lambda *a: None 

,然後導入此功能在您的其他文件中使用。

3

您應該查看工廠設計模式。它的設計基本上可以完成你正在談論的內容,儘管它可能與類而不是函數有關。這就是說,你可以通過讓一個返回兩個可能對象之一的類來獲得你想要的行爲(根據你的布爾值)。他們都有相同的方法,但它的運作方式不同(就像你的兩個功能一樣)。

Class A: 
    def method(): 
      do things one way 

Class B: 
    def method(): 
      do things another way 

    import A,B 
Class Factory: 
    def __init__(bool): 
      self.printer = A if bool else B 

    def do_thing(): 
      self.printer.method() 




import Factory 
fac = Factory(True) 
fac.do_thing() # does A thing 
fac = Factor(False) 
fac.do_thing() # does B thing