问题描述
显然我只是不知道如何在Python程序中正确导入东西。我只是从语言开始,它与我以前的Java有很大不同。
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
现在我的main.py文件看起来像..
Right now my main.py file looks like..
from Person import Person
from Person import Student
if __name__ == '__main__':
p = Person.Person("Jim", 20)
print(p)
s = Student("Jim", 20, "math")
print(s)
我一直收到错误 TypeError:'module'对象不可调用
尝试将其更改为 s = Student.Student(Jim,20,Math)
但是当发生这种情况时我最终会出现错误 TypeError:module .__ init __()最多需要2个参数(给定3个)
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)
供参考,
Person.py:
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:
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
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
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)
这篇关于Python导入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!