当前位置: 代码迷 >> 综合 >> P27 026字典:当索引不好用时1----20201005
  详细解决方案

P27 026字典:当索引不好用时1----20201005

热度:18   发布时间:2024-01-06 09:07:54.0

这里写目录标题

  • P27 026字典:当索引不好用时1----20201005
  • P31 030文件系统:介绍一个高大上的东西1006
  • P32 031永久存储:研制一缸美味的泡菜1006
  • P33 032异常处理:你不可能总是对的1--1006
  • P34 033异常处理:你不可能总是对的2--1006
  • P35 034丰富的else语句及简洁的with语句1006
  • P36 035图形用户界面入门:easygui1007
    • 安装easygui
  • P37 036类和对象:给大家介绍对象1007
  • P38 037类和对象:面向对象编程1008
  • P39 038类和对象:继承1008
  • P40 039类和对象:拾遗1008
  • P41 040类和对象:一些相关的BIF1008
  • P42 041魔法方法:构造和析构1009
  • P43 042魔法方法:算术运算1--1009
  • P44 043魔法方法:算数运算2--1010
  • P45 044魔法方法:简单定制1010
  • P46 045魔法方法:属性访问1011
  • P47 046魔法方法:描述符1024
  • P42# P42

P27 026字典:当索引不好用时1----20201005

>>> brand = ['李宁','耐克','阿迪达斯','鱼']
>>> slogan = ['一切皆有可能','just do it','impossible is nothing ','让编程改变世界']
>>> print ('鱼的口号是',slogan[brand.index('鱼')])
鱼的口号是 让编程改变世界
>>> dict1={
    '李宁':'一切皆有可能','耐克':'just do it','阿迪达斯':'impossible is nothing ','鱼':'让编程改变世界'}
>>> print('鱼的口号是',dict1['鱼'])
鱼的口号是 让编程改变世界
>>> dict2 = {
    1:'one',2,'two',3,'three'}
SyntaxError: invalid syntax
>>> dict2 = {
    1:'one',2:'two',3:'three'}
>>> dict2[2]
'two'
>>> dict3 = {
    }
>>> dict3
{
    }
>>> help(dict)
Help on class dict in module builtins:class dict(object)|  dict() -> new empty dictionary|  dict(mapping) -> new dictionary initialized from a mapping object's|      (key, value) pairs|  dict(iterable) -> new dictionary initialized as if via:|      d = {
    }|      for k, v in iterable:|          d[k] = v|  dict(**kwargs) -> new dictionary initialized with the name=value pairs|      in the keyword argument list.  For example:  dict(one=1, two=2)|  |  Methods defined here:|  |  __contains__(self, key, /)|      True if D has a key k, else False.|  |  __delitem__(self, key, /)|      Delete self[key].|  |  __eq__(self, value, /)|      Return self==value.|  |  __ge__(self, value, /)|      Return self>=value.|  |  __getattribute__(self, name, /)|      Return getattr(self, name).|  |  __getitem__(...)|      x.__getitem__(y) <==> x[y]|  |  __gt__(self, value, /)|      Return self>value.|  |  __init__(self, /, *args, **kwargs)|      Initialize self.  See help(type(self)) for accurate signature.|  |  __iter__(self, /)|      Implement iter(self).|  |  __le__(self, value, /)|      Return self<=value.|  |  __len__(self, /)|      Return len(self).|  |  __lt__(self, value, /)|      Return self<value.|  |  __ne__(self, value, /)|      Return self!=value.|  |  __new__(*args, **kwargs) from builtins.type|      Create and return a new object.  See help(type) for accurate signature.|  |  __repr__(self, /)|      Return repr(self).|  |  __setitem__(self, key, value, /)|      Set self[key] to value.|  |  __sizeof__(...)|      D.__sizeof__() -> size of D in memory, in bytes|  |  clear(...)|      D.clear() -> None.  Remove all items from D.|  |  copy(...)|      D.copy() -> a shallow copy of D|  |  fromkeys(iterable, value=None, /) from builtins.type|      Returns a new dict with keys from iterable and values equal to value.|  |  get(...)|      D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.|  |  items(...)|      D.items() -> a set-like object providing a view on D's items|  |  keys(...)|      D.keys() -> a set-like object providing a view on D's keys|  |  pop(...)|      D.pop(k[,d]) -> v, remove specified key and return the corresponding value.|      If key is not found, d is returned if given, otherwise KeyError is raised|  |  popitem(...)|      D.popitem() -> (k, v), remove and return some (key, value) pair as a|      2-tuple; but raise KeyError if D is empty.|  |  setdefault(...)|      D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D|  |  update(...)|      D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.|      If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]|      If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v|      In either case, this is followed by: for k in F:  D[k] = F[k]|  |  values(...)|      D.values() -> an object providing a view on D's values|  |  ----------------------------------------------------------------------|  Data and other attributes defined here:|  |  __hash__ = None>>> dict3 = dict((('F',70),('i',105),('h',104),('c',67)))
>>> dict3
{
    'F': 70, 'i': 105, 'h': 104, 'c': 67}
>>> dict4=(小甲鱼='让编程改变世界',苍井空='让AV征服')
SyntaxError: invalid syntax
>>> 
KeyboardInterrupt
>>> dict4=(小甲鱼='让编程改变世界',苍井空='让AV征服')
SyntaxError: invalid syntax
>>> 
KeyboardInterrupt
>>> dict4=(小甲鱼='让编程改变世界',苍井空='让AV征服')
SyntaxError: invalid syntax
>>> dict4=dict(小甲鱼='让编程改变世界',苍井空='让AV征服')
>>> dict4
{
    '小甲鱼': '让编程改变世界', '苍井空': '让AV征服'}
>>> dict4['苍井空']='学习编程'
>>> dict4
{
    '小甲鱼': '让编程改变世界', '苍井空': '学习编程'}
>>> dict4['爱迪生']= '天才'
>>> dict4
{
    '小甲鱼': '让编程改变世界', '苍井空': '学习编程', '爱迪生': '天才'}
>>> 

P31 030文件系统:介绍一个高大上的东西1006

>>> import random
>>> secret =random.randint (1,10)
>>> secret
6
>>> import os
>>> os.getcwd()
'C:\\Users\\MR\\AppData\\Local\\Programs\\Python\\Python36'
>>> os.chdir("E:")
>>> od.listdir("E:")
Traceback (most recent call last):File "<pyshell#37>", line 1, in <module>od.listdir("E:")
NameError: name 'od' is not defined
>>> os.listdir("E:")
['$RECYCLE.BIN', '360Downloads', '360驱动大师目录', 'code', 'Debug', 'Drivers', 'jianguoyun', 'Manual', 'QQMusicCache', 'record.txt', 'System Volume Information', 'test.txt', 'test_1.py.txt', '图片', '迅雷下载']
>>> os.dir("E:\\A")
Traceback (most recent call last):File "<pyshell#39>", line 1, in <module>os.dir("E:\\A")
AttributeError: module 'os' has no attribute 'dir'
>>> os.mkdir("E:\\A")
>>> os.mkdir("E:\\A\\B")
>>> os.mkdir("E:\\C\\B")
Traceback (most recent call last):File "<pyshell#42>", line 1, in <module>os.mkdir("E:\\C\\B")
FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'E:\\C\\B'
>>> os.rmdir("E:\\A\\B")
Traceback (most recent call last):File "<pyshell#43>", line 1, in <module>os.rmdir("E:\\A\\B")
OSError: [WinError 145] 目录不是空的。: 'E:\\A\\B'
>>> os.remove("E:\\A\\B\\test.txt")
>>> os.rmdir("E:\\A\\B")
>>> os.system('cmd')
-1073741510
>>> os.system('calc')
0
>>> os.curdir
'.'
>>> os.listdir(os.curdir)
['$RECYCLE.BIN', '360Downloads', '360驱动大师目录', 'A', 'code', 'Debug', 'Drivers', 'jianguoyun', 'Manual', 'QQMusicCache', 'record.txt', 'System Volume Information', 'test.txt', 'test_1.py.txt', '图片', '迅雷下载']
>>> os.path.basename('E:\\A\\B\\C\\sexy.avi')
'sexy.avi'
>>> os.path.dirname('E:\\A\\B\\C\\sexy.avi')
'E:\\A\\B\\C'
>>> os.path.join('A','B','C')
'A\\B\\C'
>>> os.path.join('C:','A','B','C')
'C:A\\B\\C'
>>> os.path.join('C:\\','A','B','C')
'C:\\A\\B\\C'
>>> os.path.split('E:\\A\\B\\C')
('E:\\A\\B', 'C')
>>> os.path.split('E:\\A\\B\\C\\test.avi')
KeyboardInterrupt
>>> os.path.split('E:\\A\\B\\C\\test.avi')
('E:\\A\\B\\C', 'test.avi')
>>> os.path.splitext('E:\\A\\B\\C\\test.avi')
('E:\\A\\B\\C\\test', '.avi')
>>> os.path.getatime('E:\\test.txt')
1601964171.0347624
>>> import time
>>> time.gmtime (os.path.getatime('E:\\test.txt'))
time.struct_time(tm_year=2020, tm_mon=10, tm_mday=6, tm_hour=6, tm_min=2, tm_sec=51, tm_wday=1, tm_yday=280, tm_isdst=0)
>>> time.localtime (os.path.getatime('E:\\test.txt'))
time.struct_time(tm_year=2020, tm_mon=10, tm_mday=6, tm_hour=14, tm_min=2, tm_sec=51, tm_wday=1, tm_yday=280, tm_isdst=0)
>>> time.localtime (os.path.getmtime('E:\\test.txt'))
time.struct_time(tm_year=2020, tm_mon=10, tm_mday=6, tm_hour=14, tm_min=2, tm_sec=51, tm_wday=1, tm_yday=280, tm_isdst=0)
>>> time.localtime (os.path.getctime('E:\\test.txt'))
time.struct_time(tm_year=2020, tm_mon=10, tm_mday=6, tm_hour=13, tm_min=15, tm_sec=14, tm_wday=1, tm_yday=280, tm_isdst=0)
>>> E:\\A\\B\\TEST.TXT
SyntaxError: unexpected character after line continuation character
>>> E:\\A\\B\\TEST.TXT
SyntaxError: unexpected character after line continuation character
>>> E:\\A\\B\\TEST.txt
SyntaxError: unexpected character after line continuation character
>>> 'E:\\A\\B\\TEST.TXT'
'E:\\A\\B\\TEST.TXT'
>>> os.path.ismount('E:\\')
True
>>> os.path.ismount('E:\\A')
False
>>> 

P32 031永久存储:研制一缸美味的泡菜1006

>>> import pickle
>>> my_list =[123,3.14,'xiaojiayu',['xnother list']]
>>> pickle_file = open("my_list.pkl",'wb')
>>> pickle.dump(my_list,pickle_file)
>>> pickle_file.close()
>>> pickle_file = open("my_list.pkl",'rb')
>>> my_list2 = pickle.load(pickle_file)
>>> print(my_list2)
[123, 3.14, 'xiaojiayu', ['xnother list']]

P33 032异常处理:你不可能总是对的1–1006

file_name = input('请输入需要打开的文件名:')
f = open(file_name,encoding='utf-8')
print('文件的内容是:')
for each_line in f:print(each_line)

常见报错类型:

>>> 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
>>> 

P34 033异常处理:你不可能总是对的2–1006

try:# int('abc')sum = 1 + '1'f = open('我为什么是一个文件.txt','r',encoding='utf-8')print(f.read())f.close()
except OSError as reason:print('文件出错啦\n错误的原因是'+str(reason))
except TypeError as reason:print('类型出错啦\n错误的原因是'+str(reason))
try:#int('abc')f = open('我为什么是一个文件.txt','w',encoding='utf-8')print(f.write('我存在了'))sum = 1 + '1'except OSError as reason:print('文件出错啦\n错误的原因是'+str(reason))
except TypeError as reason:print('类型出错啦\n错误的原因是'+str(reason))
finally:f.close()
>>> 7/0
Traceback (most recent call last):File "<pyshell#18>", line 1, in <module>7/0
ZeroDivisionError: division by zero
>>> raise ZeroDivisionError('除数为0的异常')
Traceback (most recent call last):File "<pyshell#19>", line 1, in <module>raise ZeroDivisionError('除数为0的异常')
ZeroDivisionError: 除数为0的异常

P35 034丰富的else语句及简洁的with语句1006

如果怎么样就干吧

def showMaxFactor(num):count = num//2while count > 1:if num %count ==0:print("%d最大的约数是%d"%(num,count))breakcount -= 1else: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))

P36 035图形用户界面入门:easygui1007

安装easygui

信了小甲鱼的‘鬼话’,以为要自己下载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 syswhile 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 dialogpass    #user chose continueelse:sys.exit(0)#user chose cancel

P37 036类和对象:给大家介绍对象1007

对象= 属性+方法

class Turtle:#python 中的类名约定以大写字母开头# ===关于类的一个简单例子===#属性color = 'green'weight = 10legs = 4shell = Truemouth = '大嘴'#方法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()
我是小兵
>>> 

P38 037类和对象:面向对象编程1008

self是什么?

>>> class Ball:def setName(self, name):self.name = namedef 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 = namedef 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 getNamereturn 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
'小甲鱼'

P39 038类和对象:继承1008

class DerivedClassName(BaseClassName):
import random as rclass Fish:def __init__(self):self.x = r.randint(0,10)self.y = r.randint(0,10)def move(self):self.x -= 1print('我的位置是', self.x,self.y)class Goldfish(Fish):pass
class Carp(Fish):pass
class Salmon(Fish):passclass Shark(Fish):def __init__(self):self.hungry = Truedef eat(self):if self.hungry:print('吃货的梦想天天有的吃')self.hungry =Falseelse:print('太撑了吃不下')
>>> fish = Fish()
>>> fish.move()
我的位置是 8 7
>>> fish.move()
我的位置是 7 7
>>> goldfish=Goldfish()
>>> goldfish.move()
我的位置是 6 4
>>> gildfish.move()
Traceback (most recent call last):File "<pyshell#118>", line 1, in <module>gildfish.move()
NameError: name 'gildfish' is not defined
>>> goldfish.move()
我的位置是 5 4
>>> shark = Shark()
>>> shark.eat()
吃货的梦想天天有的吃
>>> shark.eat()
太撑了吃不下
>>> shark.move()
Traceback (most recent call last):File "<pyshell#123>", line 1, in <module>shark.move()File "C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy038.py", line 10, in moveself.x -= 1
AttributeError: 'Shark' object has no attribute 'x'
>>> 

发现shark位置函数报错,原因是子类将父类函数覆盖了,改进方法:

import random as rclass Fish:def __init__(self):self.x = r.randint(0,10)self.y = r.randint(0,10)def move(self):self.x -= 1print('我的位置是', self.x,self.y)class Goldfish(Fish):pass
class Carp(Fish):pass
class Salmon(Fish):passclass Shark(Fish):def __init__(self):# Fish.__init__(self)super().__init__()self.hungry = Truedef eat(self):if self.hungry:print('吃货的梦想天天有的吃')self.hungry =Falseelse: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代言

P40 039类和对象:拾遗1008

组合

案例:

class Turtle:def __init__(self,x):self.num = xclass 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 = xself.y = ydef 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
>>> 

P41 040类和对象:一些相关的BIF1008

#issubclass()>>> class A:pass>>> class B(A):pass>>> issubclass(B,A)
True
>>> issubclass(B,B)
True
>>> issubclass(B,object)
True
>>> class C:pass>>> issubclass(B,C)
False#isinstance(object,classinfo)>>> b1=B()
>>> isinstance(b1,B)
True
>>> isinstance(b1,A)
True
>>> isinstance(b1,C)
False
>>> isinstance(b1,(A,B,C))
True#hasattr(object,name)用于判断对象是否包含对应的属性
>>> def __init__(self,x=0):self.x = x>>> c1=C()
>>> hasattr(c1,x)
Traceback (most recent call last):File "<pyshell#222>", line 1, in <module>hasattr(c1,x)
NameError: name 'x' is not defined
>>> hasattr(c1,'x')
True#getattr(object,name[,default])
>>> getattr(c1,'x')
0
>>> getattr(c1,'y')
Traceback (most recent call last):File "<pyshell#225>", line 1, in <module>getattr(c1,'y')
AttributeError: 'C' object has no attribute 'y'
>>> getattr(c1,'y','您所访问的属性不存在')
'您所访问的属性不存在'
#setattr(object,name,value)
#delattr(object,name)
>>> setattr(c1,'y','fishc')
>>> getattr(c1,'y','您所访问的属性不存在')
'fishc'
>>> delattr(c1,'y')
>>> 
>>> getattr(c1,'y','您所访问的属性不存在')
'您所访问的属性不存在'>>> class C:def __init__(self,size = 10):self.size = sizedef getSize(self):return self.sizedef setSize(self,value):self.size = valuedef delSize(self):del self.sizex = property(getSize,setSize,delSize)>>> cl = C()
>>> c1.getSize()
Traceback (most recent call last):File "<pyshell#245>", line 1, in <module>c1.getSize()
AttributeError: 'C' object has no attribute 'getSize'
>>> c1=C()
>>> c1.getSize()
10
>>> c1.x
10
>>> c1.x = 18
>>> c1.x
18
>>> c1.size
18
>>> c1.getSize()
18
>>> del c1.x
>>> c1.size
Traceback (most recent call last):File "<pyshell#254>", line 1, in <module>c1.size
AttributeError: 'C' object has no attribute 'size'
>>> 

P42 041魔法方法:构造和析构1009

魔法方法总是被双下划线包围,例如__init__

#__init__(self[,...])>>> class Rectangle:def __init__(self,x,y):self.x = xself.y = ydef getPeri(self):return(self.x+self.y)*2def 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__我被调用了
>>> 

P43 042魔法方法:算术运算1–1009

>>> type(len)
<class 'builtin_function_or_method'>
>>> type(dir)
<class 'builtin_function_or_method'>
>>> type(int)
<class 'type'>
>>> type(list)
<class 'type'>
>>> class C:pass>>> type(C)
<class 'type'>
>>> a= int('123')
>>> a
123
>>> b=int('456')
>>> a+b
579
>>> class New_int(int):def __add__(self,other):return int.__sub__(self,other)def __sub__(self,other):return int.__add__(self,other)>>> a = New_int(3)
>>> b=New_int(5)
>>> a+b
-2
>>> a-b
8
>>> class Try_int(int):def __add__(self,other):return self+otherdef __sub__(self,other)SyntaxError: invalid syntax
>>> class Try_int(int):def __add__(self,other):return self+otherdef __sub__(self,other):return self-other>>> a = Try_int(3)
>>> b = Try_int(5)
>>> a+b
Traceback (most recent call last):File "<pyshell#30>", line 1, in <module>a+bFile "<pyshell#27>", line 3, in __add__return self+otherFile "<pyshell#27>", line 3, in __add__return self+otherFile "<pyshell#27>", line 3, in __add__return self+other[Previous line repeated 328 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object
>>> class Try_int(int):def __add__(self,other):return int(self)+int(other)def __sub__(self,other):return int(self)-int(other)>>> a = Try_int(3)
>>> b = Try_int(5)
>>> a+b
8
>>> 

P44 043魔法方法:算数运算2–1010

>>> class int(int):def __add__(self,other):return int.__sub__(self,other)>>> a = int('5')
>>> a
5
>>> b=int(3)
>>> a+b
2
>>> 
=============================== RESTART: Shell ===============================
>>> class Nint(int):def __radd__(self,other):return int.__sub__(self,other)>>> a=Nint(5)
>>> b=Nint(3)
>>> a+b
8
>>> 1+b
2
>>> 
=============================== RESTART: Shell ===============================
>>> class Nint(int):def __rsub__(self,other):return int.__sub__(self,other)#注意次序>>> a=Nint(5)
>>> 3-a#先返回self后是other所以变成了self-other
2

P45 044魔法方法:简单定制1010

案例:

import time as tclass MyTimer():def __init__(self):self.prompt = '未开始计时'self.lasted = []self.start = 0self.stop = 0def __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 tclass MyTimer():def __init__(self):self.prompt = '未开始计时'self.lasted = []self.begin = 0self.end = 0def __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 tclass MyTimer():def __init__(self):self.unit = ['年','月','天','小时','分钟','秒']self.prompt = '未开始计时'self.lasted = []self.begin = 0self.end = 0def __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 = 0self.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

P46 045魔法方法:属性访问1011

>>> class C:def __init__(self):self.x ='x_man'>>> c=C()
>>> c.x
'x_man'
>>> getattr(c,'x','无此属性')
'x_man'
>>> getattr(c,'y','无此属性')
'无此属性'
>>> class C():def __init__(self,size=10):self.size =sizedef getSize(self):return self.sizedef setSize(self,value):self.size = valuedef delSize(self):del self.sizex=property(getSize,setSize,delSize)>>> c=C()
>>> c.x=1
>>> c.x
1
>>> del c.size
>>> c.x
Traceback (most recent call last):File "<pyshell#28>", line 1, in <module>c.xFile "<pyshell#23>", line 5, in getSizereturn self.size
AttributeError: 'C' object has no attribute 'size'
>>> class C:def __getattribute__(self,name):print("getattribute")return super().__getattribute__(name)def __getattr__(self,name):print("getattr")def __setattr__(self,name,value):print("setattr")return super().__setattr__(name,value)def __delattr__(self,name):print("delattr")super().__delattr__(name)>>> c=C()
>>> c.x
getattribute
getattr
>>> c.x=1
setattr
>>> c.x
getattribute
1
>>> del c.x
delattr

案例:

class Rectangle:def __init__(self,width=0,height=0):self.width = widthself.height = heightdef __setattr__(self, key, value):if key == 'square':self.width = valueself.height = valueelse:'super().__setattr__(key,value)'self.__dict__[key] = valuedef 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

P47 046魔法方法:描述符1024

P42# P42