sridhar
sridhar

Reputation: 31

is there a way to inherit the functions in a module into a class

i have a module with many functions defined in it. Is there a way to inherit all these functions into a class i have in another module.

say i have module1 with function func1(), func2()

I have another module module2 where i have a class

class class1:
    def __init__(self):
        .....
    def func3(self):
        ....

I want to inherit func1() and func2() from module1 into class1. So any object of class1 should be able to access these functions.

obj1 = class1()

I should be able to do obj1.func1()

Is there a way to acheive this in python

Upvotes: 1

Views: 787

Answers (3)

Matthew Trevor
Matthew Trevor

Reputation: 14962

If you only want to include a few functions from a module - and don't require them to be passed the instance when called - assign them as static methods to the class:

from module1 import func1, func2

class Class1(object):
    func1 = staticmethod(func1)
    func2 = staticmethod(func2)

If you want to include all of the functions, you can override __getattr__:

import module1

class Class1(object):
    def __getattr_(self, attr):
        try:
            return getattr(module1, attr)
        except AttributeError:
            # catch & re-raise with the class as the 
            # object type in the exception message
            raise AttributeError, 'Class1' object has no attribute '{}'.format(attr)

Upvotes: 0

rparent
rparent

Reputation: 628

This should do the trick.

from module1 import func1, func2

class Class1(object):

  def func3(self):
    ...

setattr(Class1, 'func1', func1)
setattr(Class1, 'func2', func2)

Be careful when you define func1 and func2 to add self as first argument.

Upvotes: 1

Germano
Germano

Reputation: 2482

You can import your functions from module1 to module2 and then map them from your class:

from module1 import func1, func2

class class1(object):
    ...
    def func1(self):
        return func1()

    def func2(self):
        return func2()

This is a bit strange, though. If your methods don't receive an instance of the class, why would you use them like that?

Upvotes: 1

Related Questions