3

I'm studying classes and OO in python and I found a problem when I try import a class from a package. The project structure and the classes are described below:

ex1/
    __init__.py
    app/
        __init__.py
        App1.py
    pojo/
        __init__.py
        Fone.py

The classes:

Fone.py

class Fone(object):

    def __init__(self,volume):
        self.change_volume(volume)

    def get_volume(self):
        return self.__volume

    def change_volume(self,volume):
        if volume >100:
            self.__volume = 100
        elif volume <0:
            self.__volume = 0
        else:
            self.__volume = volume

volume = property(get_volume,change_volume)

App1.py

from ex1.pojo import Fone

if __name__ == '__main__':
    fone = Fone(70)
    print fone.volume

    fone.change_volume(110)
    print fone.get_volume()

    fone.change_volume(-12)
    print fone.get_volume()

    fone.volume = -90
    print fone.volume

    fone.change_volume(fone.get_volume() **2)
    print fone.get_volume()

When I try use from ex1.pojo import Fone, the following Error is raised:

fone = Fone(70)
TypeError: 'module' object is not callable

But when I use from ex1.pojo.Fone import *, the program runs fine.

Why I can't import the Fone class with the way I've coded?

3 Answers 3

5

In python you can import the module or members of that module

when you do:

from ex1.pojo import Fone

you are importning your module Fone so you can use

fone = Fone.Fone(6)

or any other members of that module.

But you can also only import certain members of that module like

from ex1.pojo.Fone import Fone

I think it is worth reviewing some of the documentation on python modules, packages, and imports

Sign up to request clarification or add additional context in comments.

2 Comments

hmm, strange. I thought that the import of modules was equal to the import of classes in terms of syntax. This confused me because I'm used to construct classes in Java, but Python treats .py files as modules.Because of this, the module name has been capitalized
@AndréCaldas yes in python your module can contain multiple classes, or a multiple functions or a mix
3

You should import class, not module. Example:

from ex1.pojo.Fone import Fone

Also you should lowercase naming convention for your module names.

1 Comment

I'm used to construct classes in Java,so I thought the name of the module should come capitalized, like Java. but I enjoyed your tip about convention!
0
from ex1.pojo.Fone import Fone

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.