senara
senara

Reputation: 15

Is it possible to import a function as a class method?

I'm wondering if this is even possible.

Let's say, there are two files.

in a.py:

class A()

in b.py:

def x():  
def y():

I'd like to import a function x() from b.py to a.py's class A so that the class A has a method x.

so that i can use like this

test = A()
test.x()

Thank you!

Upvotes: 0

Views: 75

Answers (2)

Triggernometry
Triggernometry

Reputation: 583

Why not try it?

a.py

class A():
    from b import x, y

a = A()
a.x()

b.py

def x():
    print "Hi, I'm x!"


def y():
    print "Hi, I'm y!"

Yikes, that didn't work!

Traceback (most recent call last):
  File "a.py", line 6, in <module>
    a.x()
TypeError: x() takes no arguments (1 given)

But that's simple enough to fix, methods expect a class instance to be passed to them! Let's just modify b.py...

b.py, modified

def x(self):
    print "Hi, I'm x!"


def y(self):
    print "Hi, I'm y!"

Executing this will print:

Hi, I'm x!

Remember to try before you post - often the answer is as simple as "Yes, just do it!" :)

Upvotes: 1

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21453

If the functions signature doesn't allow for an instance of A to be passed as the first argument the best you can do is make them staticmethods:

import b
class A:
    x = staticmethod(b.x)
    y = staticmethod(b.y)

test = A()
test.x()

However if you had functions that could take an A instance as the first argument then it would just be:

class A:
    from b import x,y

test = A()
test.x()

Upvotes: 2

Related Questions