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?

1
  • The above error is Python2 specific. Commented Jan 25, 2017 at 17:44

3 Answers 3

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()
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.