1

Imagine I have the following test.py file

import foo

class example1(object):
      MyFunc = foo.func

Where foo.py is

def func():
      return 'Hi'

Then I write another file

import test

test.example1.MyFunc()

and get the error 'unbound method func() must be called with example1 instance as first argument (got nothing instead)'.

How can I use the function func as an attribute of the class example1?

Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
RFiischer
  • 41
  • 7

3 Answers3

2

Your problem is a python 2 specific problem. The type unbound method is deprecated in python 3. So your code is fine for python 3. Here is a well viewed answer on: What is the difference between a function, an unbound method and a bound method. Calling a unbound method in python 2 will require an instance of the corresponding class type.

There are some solutions here. Another one is, you can define your function like this:

def func(object):
    return "Hi"

As this is taking object as its first argument. Now you can write this code:

test.example1().MyFunc()
Community
  • 1
  • 1
salmanwahed
  • 9,450
  • 7
  • 32
  • 55
1

This is a Python2 issue. Change test.py to the following and it works.

import foo

class example1(object):
    MyFunc = staticmethod(foo.func)

Note that if you keep test.py as you show it, the following works:

test.example1.__dict__['MyFunc']()

This is related to the way function attributes are accessed in Python. Have a look at descriptors if you feel curious.

Here is a related question. And another one

The technicalities of the question are developped here

Community
  • 1
  • 1
Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
0

The following works for me in Python 2.7:

You are missing an __init__() method in your class definition.

foo.py should be defined as follows:

def func():
      return 'Hi'

The class should be defined as follows:

import foo

class example1():
    def __init__(self):
        self.MyFunc = foo.func

Then when you want to call attributes from the class you should instantiate it first. The tester.py script should look like this, for example:

import tester

testerInstance = tester.example1()

testerAttribute = testerInstance.MyFunc()
print testerAttribute