Sumit Bisht
Sumit Bisht

Reputation: 1517

AttributeError in trying to access a python function

I am trying to access a python function of a class into another script. This gives me the following error :

AttributeError: 'module' object has no attribute 'functionName'

The function is present in a class and is accessed via classname.functionName() call. Is there anything that I am missing ?

-update-

My code is:

(program.py)
import ImageUtils
import ...
class MyFrame(wx.Frame):
...
    ImageUtils.ProcessInformation(event)


(ImageUtils.py)
import statements... 
class ImageUtils(threading.Thread):
    def ProcessInformation(self, event):
        self.queue.put(event)

Thus, the error is : AttributeError: 'module' object has no attribute 'ProcessInformation' So, do I have to make this second script a module only ?

Upvotes: 3

Views: 8998

Answers (3)

unutbu
unutbu

Reputation: 880219

A function inside a class is called a method. You can access it from another module with

import module
module.Classname.method

However, unless that method is a special kind of method call a staticmethod or classmethod, you won't be able to call it with module.Classname.method().

Instead, you'd need to make an instance of the class:

inst=module.Classname(...)

and then call the method from the class instance:

inst.method()

The reason you were receiving the error

AttributeError: 'module' object has no attribute 'function_name'

is because module does not have a variable named function_name in its namespace. It does have a variable named Classname however. Meanwhile, Classname has a variable named function_name in its namespace. So to access the method, you need to "burrow down" to function_name by performing two attribute lookups: module.Classname.function_name.

Upvotes: 6

MD6380
MD6380

Reputation: 1007

You might want to try the dir() function to see if the function is actually present as you expect.

Example using the math module:

>>> import math
>>> dir(math)
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']

Upvotes: 1

juliomalegria
juliomalegria

Reputation: 24921

Probably you're trying to call the function from the module instead than from the class. I suggest you to do something like:

from my_module import my_class

my_class.my_function(...)
# bla bla bla

EDIT: I think Python doesn't let you use "-" in a function name.

Upvotes: 2

Related Questions