2014-11-14 40 views
2

我知道與Python類可以從其他類繼承這樣的:在Python中可能的函數是繼承嗎?

class A(object): 
    pass 

class B(A): 
    pass 

然而,這是可能的功能呢?例如,在Fab文件中,我目前有兩個功能可以完成一些相同的功能。我想要一個基本功能,這樣我可以停止重複設置。

例如:

def environment_base(): 
    #settings for both environment1 and environment2 here 

def environment1(): 
    pass 

def environment1(): 
    pass 

我知道這是什麼類的,但面料不給我用類設置的選項。

這是我的實際使用案例。我有兩個環境中布文件i..e fab environment1 commandfab environment2 command

def environment1(): 
    settings = get_settings(local_path) 
    env.git_key = settings['GIT_KEY'] 
    env.hosts = get_hosts_list(local_path) 

def environment1(): 
    settings = get_settings(local_path) 
    env.hosts = get_hosts_list(local_path) 

正如你可以看到這兩個函數有一些相同的設置和不符合「不重複自己」的原則。

+0

您必須顯式調用'environment_base'。據我所知,你所描述的任何OO語言(甚至OO理論)都不存在。 –

+2

沒有更具體的例子,很難提供建議。請注意,雖然你不能「子類化」函數,但你可以使類「__call__」。 – jonrsharpe

回答

6

這是你用什麼decorators爲神奇:

def p_decorate(func): 
    def func_wrapper(name): 
     return "<p>{0}</p>".format(func(name)) 
    return func_wrapper 

@p_decorate 
def get_text(name): 
    return "lorem ipsum, {0} dolor sit amet".format(name) 

print get_text("John") 

# Outputs <p>lorem ipsum, John dolor sit amet</p> 
+0

這也可以初始化的東西,或只有在返回值? –

+0

有很多例子 - 嘗試google python裝飾器例子 –

+0

@SteveBarnes現在我知道他們被稱爲我會:) – Prometheus

1

不,這在Python中是不可能的(或者我知道的任何其他基於OO的語言)。

您必須顯式調用environment_base

def environment_base(): 
    #settings for both environment1 and environment2 here 

def environment1(): 
    environment_base() 
    pass 

def environment1(): 
    environment_base() 
    pass 
+0

明確調用函數允許我覆蓋設置? – Prometheus

+0

@Sputnik我不知道你是如何編寫你的設置,我真的不知道。 –

2

也許我完全誤解了你的問題,但爲什麼不只是從別人援引「基地」的功能?

def environment_base(): 
    # do basic things 
    # ... 

def environment1(): 
    environment_base() 
    # do env1-specific stuff 

def environment2(): 
    environment_base() 
    # do env2-specific stuff 
+0

這就是*我所說的。 –

+0

@BartFriederichs:......好吧,偉大的思想家都會這樣想:-)請注意,我們在同一時間提交了我們的答案(9:52),我沒有看到你的答案,而你也沒有看到我的答案。必須快速輸入SO。讓我們不要開始優先訴訟:-)順便說一句,我們的解決方案比史蒂夫巴恩斯的魔法恕我直言清晰得多。 –