1

I am a newbie, and picking up Python (3.4) and trying to work on classes.

I have created a module BootstrapYieldCurve, with two classes (BootstrapYieldCurve and ForwardRates) inside.

When I import the module, I can call and manipulate the BootstrapYieldCurve class, but I get an error from calling the ForwardRates class.

Would someone be able to advise if the code is wrong, or the way I call the class in Python Shell?

>>> from BootstrapYieldCurve import ForwardRates
>>> Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    from BootstrapYieldCurve import ForwardRates
ImportError: cannot import name 'ForwardRates'

This is my module code structure

import math

class BootstrapYieldCurve():
    def __init__(self):
    def add_instrument(..........):
    ..........
class ForwardRates():
    def .........
2
  • Did you perchance already import from this module during the same session, before you wrote the ForwardRates class? Modules are cached, if you added new things, that import won't work unless you do: from importlib import reload, import BootstrapYieldCurve, reload(BootstrapYieldCurve), then repeat your from x import y statement. Commented Mar 31, 2017 at 11:01
  • hi ShadowRange, yes I did. I restarted my Python shell, and renamed the python file and classes. So, it does seem to work now. many thanks Commented Mar 31, 2017 at 14:53

1 Answer 1

1

You cannot import one class from another class like this :

from BootstrapYieldCurve import ForwardRates

because ForwardRates is not encapsulated inside BootstrapYieldCurve (Also, there is no such concept in Python). See encapsulation.

You can import variables, functions, and classes from a module (a python file that generally have variables, functions, and classes)

You can do something like :

from module_file import BootstrapYieldCurve 

and

from module_file import ForwardRates

You can refer to this basic tutorial on importing modules.

Also, try not to name module and class with same name as that may create confusion. It is a not a good practice to do that as module names share the same namespace as everything else.

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

1 Comment

Thanks Satish, I've changed my filename to be YieldCurve.py where I specify the classes BootstrapYieldCurve and ForwardRates inside. Then, I am able to import the ForwardRates using ' >>> from YieldCurve import ForwardRates'

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.