Python中的函数继承是否可行?

Pro*_*eus 2 python

我知道Python类可以继承其他类,如下所示:

class A(object):
  pass

class B(A):
  pass
Run Code Online (Sandbox Code Playgroud)

但是,这可能与功能有关吗?例如,在Fab文件中,我目前有两个函数,它们执行一些相同的操作.我想要一个基本功能,所以我可以停止重复设置.

例如:

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

def environment1():
    pass

def environment1():
    pass
Run Code Online (Sandbox Code Playgroud)

我知道这是什么类,但Fabric没有给我选择使用类进行设置.

这是我的实际用例.我有一个Fabric文件,它有两个环境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)
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这两个功能都具有一些相同的设置,并且不符合"不要重复自己"的原则.

Ste*_*nes 6

这就是你使用装饰魔术的原因:

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>
Run Code Online (Sandbox Code Playgroud)