Spencer
Spencer

Reputation: 1

How do I import a python script as a module from the python console?

I have written a python script that defines a class and creates some objects. I want to be able to work with the objects from the python console, but I can't figure out how.

For example, if I had defined a class and created an object in a file called Elements.py:

class Element:

    def __init__(self, name, protons, mass):
        self.name = name
        self.protons = protons
        self.mass = mass

element_Al = Element('Aluminium', 13, 26.982)

I thought that from the python console I could do the following to access the object's information:

import Elements.py

print(element_Al.mass)

I assumed that this would print 26.982, however this doesn't work (even though I am in the same directory as the file). What am I doing wrong?

Upvotes: 0

Views: 73

Answers (1)

kvorobiev
kvorobiev

Reputation: 5070

You can try:

from Elements import *
print(element_Al.mass)

or

import Elements
print(Elements.element_Al.mass)

Upvotes: 1

Related Questions