Reputation: 67
The online search has been less then helpful in this matter. I'm trying just to create a module with a few classes and test it. I haven't been able to pass the first part. I have created a simple class with 3 attributes and their getters methods so I see their attributes from a "main" method (I guess)
I need to create a few objects of this class so I can used the later.
the class definition is
class Person:
def __init__(self, n, a, s):
self.name = n
self.age = a
self.sex = s
def getAge(self):
return self.age
def getSex(self):
return self.sex
I saved this file in a test.py file, the from the shell I import it but then I keep getting the same error when I instantiate and object
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x = Person('myname', 10, 'm')
NameError: name 'Person' is not defined
test.py is located in C:/Python3.x directory so I really don't get this error.
When I just type the whole class in the shell and instantiate objects everything works but that is useless in my case since the modules will be growing over time.
Please answer only if you are willing to help, don't send me to the same tutorials which don't explain anything without the shell. I need to work with modules and understand the meaning of that error im getting.
Upvotes: 5
Views: 6836
Reputation: 2829
Your class should probably derive from object
, but that's not the cause of the error. You're probably trying to access a name that's not explicitly imported. You can either import a whole module, or a name from a module.
import test
test.Person()
Or
from test import Person
Person()
Or both. No error, but not much sense made either.
You may be tempted to type from test import *
to imitate behavior of other languages, but this is in most cases considered bad style in python. Explicit is better than implicit.
To learn more about how imports work, try to import test
and then dir(test)
. Or import itertools
and dir(itertools)
, or download some nice codebase like Werkzeug, read the code to see how it's structured and then try navigating it via the REPL.
Upvotes: 8