Python – Inherits loading classes from packages

Inherits loading classes from packages… here is a solution to the problem.

Inherits loading classes from packages

The structure is as follows:

app.py
  /package
    __init__.py
    foo.py
    bar.py

“foo.py” and “

bar.py” contain classes “Foo” and “Bar”. The “Foo” class inherits from the “Bar” class. We have the following code in the file….

“Application .py”:

from package import Foo

print Foo()

“__init__.py”:

from foo import Foo
from bar import Bar

“foo.py”:

class Foo(Bar):
    pass

“bar.py”:

class Bar:
    pass

If I create an instance from “Foo”, I get the name error “Name ‘Bar’ undefined”. What do I have to do to make it work? If important, I’m using Python 2.6.6….

.oO (I’m new to Python).

Solution

You need this line

from bar import Bar

In file foo.py (not only __init.py__).

Related Problems and Solutions