自定义类,保存成Athlete.py文件
class Athlete:
def __init__(self, a_name, a_dob=None, a_times=[]):
self.name = a_name
self.dob = a_dob
self.times = a_times
在IDLE中调用
>>> import Athlete
>>> sarah = Athlete('Sarah Sweeney', '2002-6-17', ['1.58','2.02','2:56'])
报如下错误:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
sarah = Athlete('Sarah Sweeney', '2002-6-17', ['1.58','2.02','2:56'])
TypeError: 'module' object is not callable
原因,没有导入类的路径
import Athlete
sarah = Athlete.Athlete('Sarah Sweeney', '2002-6-17', ['1.58','2.02','2:56'])
或者
from Athlete import Athlete
sarah = Athlete('Sarah Sweeney', '2002-6-17', ['1.58','2.02','2:56'])
本文介绍了一个名为Athlete的自定义类的创建过程,并详细解释了如何在Python环境中正确导入和使用该类。通过实例演示了常见导入错误及其解决方法。
1万+

被折叠的 条评论
为什么被折叠?



