Python import issue
So apparently I just don't know how to import things correctly in a Python program. I'm just starting with the language, and it's much different from the Java that I'm used to.
Anyway, the main problem is that there's something wrong with how I'm importing packages/modules/classes and I can't seem to figure out what it is.
Right now my file structure looks like:
-Main Directory
main.py
-Person (Folder)
__init__.py
Person.py
Student.py
Right now my main.py file looks like..
from Person import Person
from Person import Student
if __name__ == '__main__':
p = Per开发者_如何学编程son.Person("Jim", 20)
print(p)
s = Student("Jim", 20, "math")
print(s)
and I keep getting an error of TypeError: 'module' object is not callable
Have tried changing it to be s = Student.Student("Jim", 20, "Math")
but when that happens I end up with an error of TypeError: module.__init__() takes at most 2 arguments (3 given)
For reference,
Person.py:
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "My name is {0} and I am {1}".format(self.name, self.age)
Student.py:
from Person import Person
class Student(Person.Person):
def __init__(self, name, age, sub):
Person.__init__(self,name,age)
self.sub = sub
No matter what I do to the imports or anything I can seem to change, it all keeps giving me errors. No idea what to do at this point - maybe I just missed the creating of classes and subclasses when it was shown to me, but I can't figure out anything to fix it.
main.py:
from Person import Person
from Person import Student
if __name__ == '__main__':
p = Person.Person("Jim", 20)
print(p)
s = Student.Student("Jim", 20, "math")
print(s)
student.py
from Person import Person
class Student(Person):
def __init__(self, name, age, sub):
super(Student, self).__init__(name,age)
self.sub = sub
person.py
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "My name is {0} and I am {1}".format(self.name, self.age)
The problem is in your Student class. Here, Person refers to the Person.py module. You should call the parent object by doing:
super().__init__(name,age)
Also, in the main part, you should initialize:
s = Student.Student("Jim", 20, "math")
精彩评论