2017-03-07 43 views
1

我想寫一個模塊,它包含一個函數func。由於技術細節,它需要一個參數tech。由於tech是關於技術細節,因此tech具有默認值,很少需要任何更改。我想出了兩種方法來對付它:一個很少需要的參數的Python函數

  1. 休假tech是的func一些默認值的參數。問題是我有很多其他函數調用這個函數,例如,gunc,hunc ...爲了讓用戶更改tech,所有這些調用函數gunc,hunc都需要tech參數,它不那麼簡潔。

  2. 使tech成爲一個全局變量並允許用戶更改它。這裏的問題是func現在很容易受到副作用的影響,這似乎是一個糟糕的設計。

那麼我該如何處理tech的說法呢?

編輯

提供更多的信息,作爲評論所指出的,這裏有一個例子:

def func(room, tech): 
    """ 
    calculate how many lights we need to illuminate a room 
    param tech: True if the owner wants the room to be more bright, so 
    add some lights. This is seldom used since most people are 
    satisfied. 
    """ 
    # do calculation 
    return result 

def gunc(room): 
    """ 
    calculate how much money it takes to light a room. 
    """ 
    return result 

# here's many other functions 

def hunc(company) 
    """ 
    calculate how much money it takes to run a company 
    """ 
    for room in company.rooms: 
     money += gunc(room) 
    money += many many other costs 
    return money 

在這個例子中,它沒有任何意義的,在hunc一個tech說法。畢竟,公司經營公司究竟與房間主人需要多少燈有關?此外,如果hunc需要tech參數,則必須採取無數其他技術參數,這是不可接受的。

+3

我認爲'func','gunc'和'hunc'的示例函數將幫助我圍繞這個問題進行思考。 –

+0

只有當你的應用程序有意義時:使'Tech'成爲一個類,'Tech()'具有默認值的實例並且讓'hunc'&'func'成爲方法。 – VPfB

回答

1

我想你會想跟蹤狀態,但我會避免使用全局變量。相反,我會將技術參數封裝在一個類中。

class Room: 
    def __init__(self, bright=False): 
     self.bright = bright 

    @property 
    def lights(self): 
     if self.bright: 
      return 42 
     return 21 

    @property 
    def lighting_cost(self): 
     return self.lights * 10 


class Building: 
    def __init__(self, rooms): 
     self.rooms = rooms 

    @property 
    def total_lighting_cost(self): 
     return sum(room.lighting_cost for room in self.rooms) 


room_a = Room() 
room_b = Room(bright=True) 
building = Building([room_a, room_b]) 

print building.total_lighting_cost # 630 = 210 + 420 

這使用屬性,但它們很容易被適當命名的方法替換。

1

如果您希望呼叫gunchunc的用戶能夠更改tech,那麼您應該將其作爲這些功能的默認參數。

雖然默認的可能是「無」,如果它不是沒有tech參數設置爲不同的東西,gunchunc通話func

這樣,您只需要在func中定義一次缺省值tech,但是您可以避免使用全局變量。

例子:

def func(tech=42): 
    print(tech) 


def gunc(my_param, tech=None): 

    if tech: 
     func(tech) 
    else: 
     func() 


# call hunc with default tech 
gunc('Hello') 

# specify tech 
gunc('Hello', tech=7) 
+0

+1,但是在'func'本身默認爲'None'會更清晰一些,在'func'中放入'如果tech是None:tech = 42',然後'gunc'和所有人否則總是可以在不需要條件的情況下調用'func(tech)'。 – tzaman

+0

嗯,可能是對的,但我認爲上面的例子可能對閱讀和維護代碼更清晰。判決電話。 – uvesten

+1

是的,但是你必須拋棄'func'被調用的地方'if/else',並且忘記會導致問題。另一個問題是'gunc()'和'gunc(tech = None)'是等價的,但是'func()'和'func(tech = None)'不會導致混淆和錯誤。 – tzaman

0

簡單:

default_value = 10 #an example,can be anything 
called_tech_value = 9 #you decide 
def func(tech = default_value,tech_for_calls = called_tech_value): 
    pass 

所有你需要做的是使用其他功能變量tech_for_calls。

+0

我完全不明白答案。你有'gunc'的例子嗎? –

+0

這沒有任何意義。 'func'應該如何決定使用哪個版本的'tech'? – tzaman

相關問題