常见报错类型:
>>> my_list = ['小甲鱼是帅哥'] >>> assert len(my_list) > 0 >>> my_list.pop() '小甲鱼是帅哥' >>> assert len(my_list) >0 Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> assert len(my_list) >0 AssertionError >>> my_list.fishc Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> my_list.fishc AttributeError: 'list' object has no attribute 'fishc' >>> my_list = [1,2,3] >>> my_liat[3] Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> my_liat[3] NameError: name 'my_liat' is not defined >>> my_list[2] 3 >>> my_dixt = {'one' : 1,'two':2,'three':3} >>> my_dict["one"] Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> my_dict["one"] NameError: name 'my_dict' is not defined >>> my_dict['one'] Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> my_dict['one'] NameError: name 'my_dict' is not defined >>> my_dixt['one'] 1 >>> my_dixt['four'] Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> my_dixt['four'] KeyError: 'four' >>> my_dixt.get('four') >>> my_dixt {'one': 1, 'two': 2, 'three': 3} >>> fishc Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> fishc NameError: name 'fishc' is not defined >>> print'i love' SyntaxError: invalid syntax >>> 1+'1' Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> 1+'1' TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> 7/0 Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> 7/0 ZeroDivisionError: division by zero >>>如果怎么样就干吧
def showMaxFactor(num): count = num//2 while count > 1: if num %count ==0: print("%d最大的约数是%d"%(num,count)) break count -= 1 else: print('%d是素数!'%num) num = int(input('请输入一个数:')) showMaxFactor(num) try: # int('abc') int('123') except ValueError as reason: print('出错啦'+str(reason)) else: print('没有任何异常') # try: # f =open('data.txt','w',encoding='utf-8') # for each_line in f: # print(each_line) # except OSError as reason: # print('出错啦'+str(reason)) # finally: # f.close() try: with open('data.txt','w',encoding='utf-8') as f: for each_line in f: print(each_line) except OSError as reason: print('出错啦'+str(reason))信了小甲鱼的‘鬼话’,以为要自己下载easygui,一看教程全部要在网上下载Python的工具包easygui-0.96或easygui-0.97,而这个工具包不是要fq到官网下载,就是要付费。。。既然白嫖当然要贯彻到底咯,功夫不负穷孩子,终于找到了一个直接cmd安装的,操作超级简单网址拿走不谢
不过以防万一,附上我的所有骚操作,害怕疏漏,我是先安装的pycharm中的easygui最后直接命令行接着上面网址的输入pip,没有下载pip,就显示已有。 就大功告成了,不知道有没有关系
pycharm中easygui安装的方法
file->settings->project:->project interpreter 右侧加号+ 搜索 easygui,点击instal安装即可 import easygui as g import sys while 1: g.msgbox('hi,欢迎进入第一个界面小游戏') msg = '请问你希望在工作室学到什么知识呀?' title = '小游戏互动' choices = ['谈恋爱','编程','emm','琴棋书画'] choice = g.choicebox(msg,title,choices) #note that we convert choice to string, in case #the user canceled the choice, and we got none. g.msgbox('你的选择是:'+str(choice),'结果') msg = '你希望重新开始小游戏吗' title = '请选择' if g.ccbox(msg,title): #show a continue/cancel dialog pass #user chose continue else: sys.exit(0)#user chose cancel对象= 属性+方法
class Turtle:#python 中的类名约定以大写字母开头 # ===关于类的一个简单例子=== #属性 color = 'green' weight = 10 legs = 4 shell = True mouth = '大嘴' #方法 def climb(self): print('我正在努力的向前爬') def run(self): print('我正在飞快的向前跑') def bite(self): print('咬死你') def eat(self): print('有的吃满足。。') def sleep(self): print('困了') >>> import turtle >>> tt = Turtle() Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> tt = Turtle() NameError: name 'Turtle' is not defined >>> tt = Turtle() Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> tt = Turtle() NameError: name 'Turtle' is not defined >>> Turtle() Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> Turtle() NameError: name 'Turtle' is not defined >>> Turtle().climb() Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> Turtle().climb() NameError: name 'Turtle' is not defined >>> import Turtle Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> import Turtle ModuleNotFoundError: No module named 'Turtle' >>> import turtle >>> tt = turtle() Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> tt = turtle() TypeError: 'module' object is not callable >>> === RESTART: C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy036.py === >>> tt = Turtle() >>> Turtle() <__main__.Turtle object at 0x00000210B04396A0> >>> tt.climb() 我正在努力的向前爬 >>> tt.bite() 咬死你 >>> tt.sleep() 困了 >>>我可能就是传说中的憨憨本人了,这个地方小甲鱼明明是运行了第一个Turtle()文件,我以为他是在交互页面,害,听课不积极,早晚出问题。 继承
>>> list1=[2,1,3,5,7] >>> list.sort() Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> list.sort() TypeError: descriptor 'sort' of 'list' object needs an argument >>> list1.sort() >>> list1 [1, 2, 3, 5, 7] >>> list1.append(9) >>> liat1 Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> liat1 NameError: name 'liat1' is not defined >>> list1 [1, 2, 3, 5, 7, 9] >>> class Mylist(list): pass >>> list2 = Mylist() >>> list2.append(5) >>> list2 [5] >>> list2.append(2) >>> list.sort()#排序 Traceback (most recent call last): File "<pyshell#27>", line 1, in <module> list.sort() TypeError: descriptor 'sort' of 'list' object needs an argument >>> list2.sort() >>> list2 [2, 5]多态:不同对象对同一方法响应不同的行动
>>> class A: def fun(self): print('我是小啊') >>> class B: def fun(self): print('我是小兵') >>> a=A() >>> b=B() >>> a.fun() 我是小啊 >>> a.fun() 我是小啊 >>> b.fun() 我是小兵 >>>self是什么?
>>> class Ball: def setName(self, name): self.name = name def kick(self): print("我叫%s,该死的,谁踢我"% self.name) >>> a= Ball() >>> a.setName('球a') >>> a.kick() 我叫球a,该死的,谁踢我 __init__(self,param1,param2...) >>> class Ball: def __init__(self,name): self.name = name def kick(self): print("我叫%s,该死的,谁踢我"% self.name) >>> b=Ball('tomato') >>> b.kick() 我叫tomato,该死的,谁踢我 >>> >>> class Person: name = '小甲鱼' >>> p = Person() >>> p,name Traceback (most recent call last): File "<pyshell#75>", line 1, in <module> p,name NameError: name 'name' is not defined >>> p.name() Traceback (most recent call last): File "<pyshell#76>", line 1, in <module> p.name() TypeError: 'str' object is not callable >>> p.name '小甲鱼' >>> class Person: __name = '小甲鱼'#公有变私有 >>> p = Person() >>> p.name Traceback (most recent call last): File "<pyshell#81>", line 1, in <module> p.name AttributeError: 'Person' object has no attribute 'name' >>> class Person: __name = '小甲鱼' def getName(self): return self._name#应该是双下划线 >>> p=Person() >>> p.name Traceback (most recent call last): File "<pyshell#87>", line 1, in <module> p.name AttributeError: 'Person' object has no attribute 'name' >>> p.getName() Traceback (most recent call last): File "<pyshell#88>", line 1, in <module> p.getName() File "<pyshell#85>", line 4, in getName return self._name AttributeError: 'Person' object has no attribute '_name' >>> class Person: __name = '小甲鱼' def getName(self): return self.__name >>> p = Person() >>> p.name Traceback (most recent call last): File "<pyshell#92>", line 1, in <module> p.name AttributeError: 'Person' object has no attribute 'name' >>> p.getName() '小甲鱼' >>> p._Person__name '小甲鱼'发现shark位置函数报错,原因是子类将父类函数覆盖了,改进方法:
import random as r class Fish: def __init__(self): self.x = r.randint(0,10) self.y = r.randint(0,10) def move(self): self.x -= 1 print('我的位置是', self.x,self.y) class Goldfish(Fish): pass class Carp(Fish): pass class Salmon(Fish): pass class Shark(Fish): def __init__(self): # Fish.__init__(self) super().__init__() self.hungry = True def eat(self): if self.hungry: print('吃货的梦想天天有的吃') self.hungry =False else: print('太撑了吃不下')运行结果
=== RESTART: C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy038.py === >>> shark = Shark() >>> shark.move() 我的位置是 1 4 >>> Fish.__init__(shark) >>> shark.move() 我的位置是 0 0 >>> Fish.__init__() Traceback (most recent call last): File "<pyshell#128>", line 1, in <module> Fish.__init__() TypeError: __init__() missing 1 required positional argument: 'self' >>> === RESTART: C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy038.py === >>> shark = Shark() Traceback (most recent call last): File "<pyshell#129>", line 1, in <module> shark = Shark() File "C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy038.py", line 23, in __init__ super()>__init__() NameError: name '__init__' is not defined >>> === RESTART: C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy038.py === >>> shark = Shark() >>> shark.move() >>> class Base1: def fool(self): print("我是fool,我为Base1代言") >>> class Base2: def foo2(self): print("我是foo2,我为Base2代言") >>> class C(Base1,Base2): pass >>> c=C() >>> c.fool() 我是fool,我为Base1代言 >>> c.foo2() 我是foo2,我为Base2代言组合
案例:
class Turtle: def __init__(self,x): self.num = x class Fish: def __init__(self,x): self.num = x class Pool: def __init__(self,x,y): self.turtle = Turtle(x) self.fish = Fish(y) def print_num(self): print("水池里总共有乌龟%d 只,鱼 %d 条"%(self.turtle.num,self.fish.num))输出:
=== RESTART: C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy039.py === >>> pool = Pool(1,10) >>> pool.print_num() 水池里总共有乌龟1 只,鱼 10 条类、类对象和实例对象
>>> class C: count = 0 >>> a=C() >>> b=C() >>> c=C() >>> a.count 0 >>> b.count 0 >>> c.count 0 >>> c.count += 10 >>> c.count 10 >>> a.count 0 >>> b.count 0 >>> C.count 0 >>> C.count += 10 >>> a.count 10 >>> C.count = 100 >>> a.count 100 >>> b.count 100 >>> c.count 10 >>> class C: def x(self): print("X-man") >>> c=C() >>> c.x() X-man >>> c.x=1 >>> c.x 1 >>> c.x() Traceback (most recent call last): File "<pyshell#174>", line 1, in <module> c.x() TypeError: 'int' object is not callable >>> class BB: def printBB(): print('no zuo no die') >>> BB.printBB() no zuo no die >>> bb = BB() >>> bb.printBB() Traceback (most recent call last): File "<pyshell#181>", line 1, in <module> bb.printBB() TypeError: printBB() takes 0 positional arguments but 1 was given >>> class CC: def setXY(self, x, y): self.x = x self.y = y def printXY(self): print(self.x,self.y) >>> dd = CC() >>> dd.__dict__ {} >>> CC.__dict__ mappingproxy({'__module__': '__main__', 'setXY': <function CC.setXY at 0x0000022AB8990510>, 'printXY': <function CC.printXY at 0x0000022AB8990598>, '__dict__': <attribute '__dict__' of 'CC' objects>, '__weakref__': <attribute '__weakref__' of 'CC' objects>, '__doc__': None}) >>> dd.setXY(4,5) >>> dd.__dict__ {'x': 4, 'y': 5} >>> CC.__dict__ mappingproxy({'__module__': '__main__', 'setXY': <function CC.setXY at 0x0000022AB8990510>, 'printXY': <function CC.printXY at 0x0000022AB8990598>, '__dict__': <attribute '__dict__' of 'CC' objects>, '__weakref__': <attribute '__weakref__' of 'CC' objects>, '__doc__': None}) >>> del CC >>> ee = CC() Traceback (most recent call last): File "<pyshell#196>", line 1, in <module> ee = CC() NameError: name 'CC' is not defined >>> dd.printXY() 4 5 >>>魔法方法总是被双下划线包围,例如__init__
#__init__(self[,...]) >>> class Rectangle: def __init__(self,x,y): self.x = x self.y = y def getPeri(self): return(self.x+self.y)*2 def getArea(self): return self.x*self.y >>> rect = Rectangle(3,4) >>> rect.getPeri() 14 >>> >>> rect.getArea() 12 >>> class A: def __init__(self): return 'A for Acup' >>> a=A() Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> a=A() TypeError: __init__() should return None, not 'str' #__new__(cls[,...]) >>> class CapStr(str): def __new__(cls,string): string = string.upper() return str.__new__(cls,string) >>> a = CapStr('I love fish') >>> a 'I LOVE FISH' #__del__(self) >>> class C: def __init__(self): print('i am __init__我被调用了') def __del__(self): print('i am __del__我被调用了') >>> c1=C() i am __init__我被调用了 >>> c2=c1 >>> c3=c2 >>> del c3 >>> del c2 >>> del c1 i am __del__我被调用了 >>>案例:
import time as t class MyTimer(): def __init__(self): self.prompt = '未开始计时' self.lasted = [] self.start = 0 self.stop = 0 def __str__(self): return self.prompt __repr__ = __str__ #开始计时 def start(self): self.start = t.localtime() print('计时开始') #停止计时 def stop(self): self.stop = t.localtime() self._calc() print('计时结束 ') #内部方法计算运行时间 def _calc(self): self.lasted = [] self.prompt = '总共运行了' for index in range(6): self.lasted.append(self.stop[index] - self.start[index]) self.prompt += str(self.lasted[index]) # print(self.prompt)结果:
=== RESTART: C:/Users/MR/AppData/Local/Programs/Python/Python36 === RESTART: C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy044.py === >>> t1 = MyTimer() >>> t1 未开始计时 >>> t1.start() Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> t1.start() TypeError: 'int' object is not callable#原因:将start进行初始化,默认为int型,进而属性覆盖方法改进:
import time as t class MyTimer(): def __init__(self): self.prompt = '未开始计时' self.lasted = [] self.begin = 0 self.end = 0 def __str__(self): return self.prompt __repr__ = __str__ #开始计时 def start(self): self.begin = t.localtime() print('计时开始') #停止计时 def stop(self): self.end = t.localtime() self._calc() print('计时结束 ') #内部方法计算运行时间 def _calc(self): self.lasted = [] self.prompt = '总共运行了' for index in range(6): self.lasted.append(self.end[index] - self.begin[index]) self.prompt += str(self.lasted[index]) # print(self.prompt)结果:
=== RESTART: C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy044.py === >>> t1 = MyTimer() >>> t1 未开始计时 >>> t1.start <bound method MyTimer.start of 未开始计时> >>> t1.start() 计时开始 import time as t class MyTimer(): def __init__(self): self.unit = ['年','月','天','小时','分钟','秒'] self.prompt = '未开始计时' self.lasted = [] self.begin = 0 self.end = 0 def __str__(self): return self.prompt __repr__ = __str__ def __add__(self,other): prompt = "总共运行了" result =[] for index in range(6): result.append(self,lasted[index] +other.lasted[index]) if result[index]: prompt += (str(result[index])+self.unit[index]) return prompt #开始计时 def start(self): self.begin = t.localtime() self.prompt = "提示:请先用stop()停止计时" print('计时开始') #停止计时 def stop(self): if not self.begin: print('请先调用start()进行计时') else: self.end = t.localtime() self._calc() print('计时结束 ') #内部方法计算运行时间 def _calc(self): self.lasted = [] self.prompt = '总共运行了' for index in range(6): self.lasted.append(self.end[index] - self.begin[index]) if self.lasted[index]: self.prompt += (str(self.lasted[index])+self.unit[index]) # print(self.prompt) #为下一轮计时初始化变量 self.begin = 0 self.end = 0运行:
=== RESTART: C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy044.py === >>> t1 = MyTimer() >>> t1.stop() 请先调用start()进行计时 >>> t1.start() 计时开始 >>> t1 提示:请先用stop()停止计时 >>> t1.stop() 计时结束 >>> t1 总共运行了1分钟-52秒案例:
class Rectangle: def __init__(self,width=0,height=0): self.width = width self.height = height def __setattr__(self, key, value): if key == 'square': self.width = value self.height = value else: 'super().__setattr__(key,value)' self.__dict__[key] = value def getArea(self): return self.width * self.height输出:
>>> r1=Rectangle(4,5) >>> r1.getArea() 20 >>> r1.square = 10 >>> r1.width 10 >>> r1.height 10 >>> r1.getArea() 100