Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is inheritance in functions possible in Python?

Tags:

python

I know with Python classes you can inherit from other classes like this:

class A(object):
  pass

class B(A):
  pass

However, is this possible with functions? For example, in a Fab file I currently have two functions which do some of the same stuff. I would like a base function so I can stop the duplication of settings.

For example:

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

def environment1():
    pass

def environment1():
    pass

I know this is what classes are for but Fabric does not give me the option of using classes for settings.

This is my actual use-case. I have a Fabric file which has two environments i..e fab environment1 command or fab 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)

As you can see both functions have some of the same settings and does not meet the "Don't Repeat Yourself" principle.

like image 222
Prometheus Avatar asked Nov 29 '25 06:11

Prometheus


1 Answers

This is what you use the magic of decorators for:

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>
like image 199
Steve Barnes Avatar answered Dec 01 '25 18:12

Steve Barnes