tags:

views:

104

answers:

4

I have into my main.py

from modules import controller
ctrl = controller
help(ctrl)
print(ctrl.div(5,2))

and the controllor.py is:

class controller:
    def div(self, x, y): 
        return x // y

when I run my main I got the error:

Traceback (most recent call last):
  File "...\main.py", line 8, in ?
    print(ctrl.div(5,2))
AttributeError: 'module' object has no attribute 'div'

WHat is wrong?

+1  A: 

You should create an instance of controller, like this:

ctrl = controller()

Note the brackets after controller.

Ryan Duffield
+3  A: 

ctrl = controller

‘controller’ is a module, representing your whole ‘controller.py’ file. In Python, unlike in Java, there can be any number of symbols defined inside a module, so there isn't a 1:1 relationship between the imported module and the class defined in it.

So the script complains because the ‘controller’ module does not have a ‘div’ function; ‘div’ is defined as a method of the ‘controller’ class inside the ‘controller’ module. If you want an instance of the controller() class you need to say:

ctrl= controller.controller()

(Note also the () to instantiate the object, or you'll be getting the class itself rather than an instance. If you do really want to define a static method in the class so you can call it without an instance, you can do this using the ‘staticmethod’ decorator and omitting ‘self’.)

It's usually best to name your classes with an initial capital to avoid confusion:

class Controller(object):
    ...

ctrl= controller.Controller()
bobince
yes it works but not using initial capital
DrFalk3n
+3  A: 

This is very confusing as shown.

When you say

from modules import controller

You're making the claim that you have a module with a filename of modules.py.

OR

You're making the claim that you have a package named modules. This directory has an __init__.py file and a module with a filename of controller.py

You should clarify this to be precise. It looks like you have mis-named your files and modules in the the example code posted here.

When you say

from modules import controller

That creates a module (not a class) named controller.

When you say

ctrl = controller

That creates another name for the controller module, ctrl.

At no time to you reference the class (controller.controller). At no time did you create an instance of the class (controller.controller()).

S.Lott
A: 

When you execute following code

from modules import controller
ctrl = controller

ctrl variable becomes a pointer to controller class. To create an instance of controller class you need to add parenthesis:

from modules import controller
ctrl = controller()
Glorphindale