发布时间:2019-09-07 08:12:04编辑:auto阅读(1518)
class Cat(Animal) 括号中为该类的父类列表
class Animal:
__count=100
heigtht=0
def showcount3(self):
print(self.__count)
class Cat(Animal):
name='cat'
__count=200
c=Cat()
c.showcount3()
结果为100
因为子类调用了父类获取父类私有变量的方法 self.count的count作用域是在父类下的,其真正调用的self._Animal__count,而这个属性只有父类有
一个类继承自多个类就是多继承,他将具有多个类的特征
通常不能独立工作,因为它是准备混入别的类中的部分功能实现
其祖先类也应是Mixin类
使用Mixin时,其通常在继承列表的第一个位置
def printable(cls):
def _print(self):
print(self.content, 'decorator')
cls.print = _print
return cls
class Document:
def __init__(self, content):
self.content = content
class Word(Document):
pass
class Pdf(Document):
pass
@printable
class PrintableWord(Word): pass
print(PrintableWord.__dict__)
print(PrintableWord.mro())
pw = PrintableWord('test string')
pw.print()
@printable
class PrintablePdf(Word):
pass
class Document:
def __init__(self, content):
self.content = content
class Word(Document):
pass
class Pdf(Document):
pass
class PrintableMixin:
def print(self):
print(self.content, 'Mixin')
class PrintableWord(PrintableMixin, Word):
pass
print(PrintableWord.__dict__)
print(PrintableWord.mro())
pw = PrintableWord('test string')
pw.print()
class SuperPrintableMixin(PrintableMixin):
def print(self):
print('~' * 20)
super().print()
print('~' * 20)
class SuperPrintablePdf(SuperPrintableMixin, Pdf):
pass
print(SuperPrintablePdf.__dict__)
print(SuperPrintablePdf.mro())
spp = SuperPrintablePdf('super print pdf')
spp.print()
lst = [37, 99, 73, 48, 47, 40, 40, 25, 99, 51]
lst.sort()
def bi_insert(lst, value):
high = len(lst)
low = 0
while low < high:
mid = (low + high) // 2
if value > lst[mid]:
low = mid + 1
else:
high = mid - 1
lst.insert(low, value)
bi_insert(lst, 100)
bi_insert(lst, 40)
print(lst)
bisect.bisect_left(a, x, lo=0, hi=len(a))
bisect.bisect_right(a, x, lo=0, hi=len(a))
bisect.insort_left(a, x, lo=0, hi=len(a))
import bisect
def get_grade(score):
breakpoints = [60, 70, 80, 90]
grades = 'EDCBA'
return grade[bisect.bisect(breakpoints, score)]
for x in (50,60,69,79,85,100):
print('{} -> {}'.format(x,get_grade(x)))
如果提供dir(),则返回属性列表,否则会尽量从dict属性中收集信息
对应==,判断两个对象是否相等,返回bool类型
对象去重时
去重一定需要t提供eq方法
<,<=,==,>,>=,!=
+,-,*,/,%,//,**,divmod
+=,-=,*=,/=,%=,//=,**=
习题 完成Point类,实现判断点相等,并完成向量加法
习题 改造购物车类成方便操作的容器类
call
习题 实现斐波那契类,对象可调用
class Fibonacci:
def __init__(self):
self.lst = [0, 1, 1]
def __call__(self, index):
if index < 0:
raise Exception()
self.generator(index)
return self[index]
def __len__(self):
return len(self.lst)
def __iter__(self):
# yield from self.lst
return iter(self.lst)
def __getitem__(self, item):
return self.lst[item]
def generator(self, index):
for i in range(len(self), index + 1):
self.lst.append(self[i - 1] + self[i - 2])
with ... as语法
exit返回值为等效True的值,则压制异常
习题 为函数执行计时
上一篇: linux snmpv3添加用户,简单理
下一篇: python 比较相同linux系统rp
47861
46424
37310
34757
29330
25989
24940
19966
19562
18049
5805°
6432°
5945°
5974°
7079°
5925°
5961°
6455°
6416°
7797°