*)假如导入出现了问题,那么一定是导入的文件里的语法问题或者其他问题
1)导入时重命名 as
from matplotlib import pyplot as plt
#使用
fig=plt.figure(1,figsize=(4,3))
2)只导入部分
from matplotlib import animation
#使用
anim=animation.FuncAnimation(fig,animate,frames=len(frames),interval=frame_interval,repeat=True)
#这样使用不行
Traceback (most recent call last):
File "visualization_sort.py", line 59, in <module>
plt,_=draw_chart('random')
File "visualization_sort.py", line 55, in draw_chart
anim=matplotlib.animation.FuncAnimation(fig,animate,frames=len(frames),interval=frame_interval,repeat=True)
NameError: name 'matplotlib' is not defined
#增加一行导入(还是不行)
import matplotlib
(sort) λ python visualization_sort.py
Traceback (most recent call last):
File "visualization_sort.py", line 59, in <module>
plt,_=draw_chart('random')
File "visualization_sort.py", line 55, in draw_chart
anim=matplotlib.animation.FuncAnimation(fig,animate,frames=len(frames),interval=frame_interval,repeat=True)
AttributeError: module 'matplotlib' has no attribute 'animation'
别的一些正确的导入:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
from Data import Data
#因为第一个Data代表的是Data.py里的Data,第二个代表的是class Data:里的Data
使用
b=data[Data.data_count//4,Data.data_count//2]
#若是import Data
AttributeError: module 'Data' has no attribute 'data_count'
Data.py里代码
class Data:
data_count=32
def __init__(self,value):
self.value=value
self.set_color()
def set_color(self,rgba=None):
if not rgba:
rgba=(0,
1-self.value/(Data.data_count*2),
self.value/(Data.data_count*2)+0.5,
1)
self.color=rgba
能重命名
from bubble_sort import bubble_sort as bubble
#使用
frames=bubble(original_data_object)
还没有明白为什么要构造出这样一种另外的方式
他精准的并且只导入你想要的,但有时会出现这样的情况
>>>form timeit import timeit #只导入了timeit.timeit
>>> timeit.default_timer() #而这个方法是第一个timeit模块的方法
Traceback (most recent call last):
File "" , line 1, in <module>
timeit.default_timer()
AttributeError: 'function' object has no attribute 'default_timer'
>>> import timeit
>>> timeit.default_timer()
370.277480676
>>>
可以这样替换
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
#这段代码与下面代码效果相同
from timeit import timeit
timeit('x=1',number=100)
#这是另一种替换方式
import timeit
timeit.timeit('x=1',number=100)
有些模块构建对象时也可以这样用
>>> x=prettytable()
Traceback (most recent call last):
File "" , line 1, in <module>
TypeError: 'module' object is not callable
>>> from prettytable import PrettyTable
>>> x=PrettyTable()
>>>
问题
1)ImportError: cannot import name ‘bidirectional_bubble_sort’
Traceback (most recent call last):
File "test_and_compared.py", line 1, in <module>
from bidirectional_bubble_sort import bidirectional_bubble_sort
ImportError: cannot import name 'bidirectional_bubble_sort'
原因:因为文件没有保存