群内编号:129-木铎铎
本笔记记录之前学习Python时不熟悉或未接触的知识点以及一些个人认为能帮助理解的例子。
今天学这个魔法方法感觉挺难的,内部机制学得云里雾里,这里留个坑,之后回来细化这个部分,下面主要写一些看懂了觉得重要的,以及在尝试理解的过程中觉得不错的一些博客,还有练习题。
当你打印一个对象的时候,触发__str__
当你使用%s格式化的时候,触发__str__
str()强转数据类型的时候,触发__str__
__repr__(self):
repr是str的备胎,有__str__的时候执行__str__
没有实现__str__的时候,执行__repr__
repr(obj)内置函数对应的结果是__repr__的返回值
当你使用%r格式化的时候 触发__repr__
__str__(self) 的返回结果可读性强。也就是说,str 的意义是得到便于人们阅读的信息,就像下面的 ‘2019-10-11’ 一样。
__repr__(self) 的返回结果应更准确。怎么说,repr 存在的目的在于调试,便于开发者使用。
import datetime
today = datetime.date.today()
print(str(today)) # 2019-10-11
print(repr(today)) # datetime.date(2019, 10, 11)
print('%s' %today) # 2019-10-11
print('%r' %today) # datetime.date(2019, 10, 11)
class C:
def __getattribute__(self, item):
print('__getattribute__')
return super().__getattribute__(item)
def __getattr__(self, item):
print('__getattr__')
def __setattr__(self, key, value):
print('__setattr__')
super().__setattr__(key, value)
def __delattr__(self, item):
print('__delattr__')
super().__delattr__(item)
c = C()
c.x
# __getattribute__
# __getattr__
c.x = 1
# __setattr__
del c.x
# __delattr__
技术图文:Python魔法方法之属性访问详解
描述符就是将某种特殊类型的类的实例指派给另一个类的属性。
class MyDecriptor:
def __get__(self, instance, owner):
print('__get__', self, instance, owner)
def __set__(self, instance, value):
print('__set__', self, instance, value)
def __delete__(self, instance):
print('__delete__', self, instance)
class Test:
x = MyDecriptor()
t = Test()
t.x
# __get__ <__main__.MyDecriptor object at 0x000000CEAAEB6B00> <__main__.Test object at 0x000000CEABDC0898>
t.x = 'x-man'
# __set__ <__main__.MyDecriptor object at 0x00000023687C6B00> <__main__.Test object at 0x00000023696B0940> x-man
del t.x
# __delete__ <__main__.MyDecriptor object at 0x000000EC9B160A90> <__main__.Test object at 0x000000EC9B160B38>
技术图文:什么是Python的描述符?
协议(Protocols)与其它编程语言中的接口很相似,它规定你哪些方法必须要定义。然而,在 Python 中的协议就显得不那么正式。事实上,在 Python 中,协议更像是一种指南。
容器类型的协议
如果说你希望定制的容器是不可变的话,你只需要定义__len__()和__getitem__()方法。
如果你希望定制的容器是可变的话,除了__len__()和__getitem__()方法,你还需要定义__setitem__()和__delitem__()两个方法。
__len__(self)定义当被len()调用时的行为(返回容器中元素的个数)。
__getitem__(self, key)定义获取容器中元素的行为,相当于self[key]。
__setitem__(self, key, value)定义设置容器中指定元素的行为,相当于self[key] = value。
__delitem__(self, key)定义删除容器中指定元素的行为,相当于del self[key]。
例1 编写一个不可改变的自定义列表,要求记录列表中每个元素被访问的次数。
class CountList:
def __init__(self, *args):
self.values = [x for x in args]
self.count = {}.fromkeys(range(len(self.values)), 0)
def __len__(self):
return len(self.values)
def __getitem__(self, item):
self.count[item] += 1
return self.values[item]
c1 = CountList(1, 3, 5, 7, 9)
c2 = CountList(2, 4, 6, 8, 10)
print(c1[1]) # 3
print(c2[2]) # 6
print(c1[1] + c2[1]) # 7
print(c1.count)
# {0: 0, 1: 2, 2: 0, 3: 0, 4: 0}
print(c2.count)
# {0: 0, 1: 1, 2: 1, 3: 0, 4: 0}
例2 编写一个可改变的自定义列表,要求记录列表中每个元素被访问的次数。
class CountList:
def __init__(self, *args):
self.values = [x for x in args]
self.count = {}.fromkeys(range(len(self.values)), 0)
def __len__(self):
return len(self.values)
def __getitem__(self, item):
self.count[item] += 1
return self.values[item]
def __setitem__(self, key, value):
self.values[key] = value
def __delitem__(self, key):
del self.values[key]
for i in range(0, len(self.values)):
if i >= key:
self.count[i] = self.count[i + 1]
self.count.pop(len(self.values))
c1 = CountList(1, 3, 5, 7, 9)
c2 = CountList(2, 4, 6, 8, 10)
print(c1[1]) # 3
print(c2[2]) # 6
c2[2] = 12
print(c1[1] + c2[2]) # 15
print(c1.count)
# {0: 0, 1: 2, 2: 0, 3: 0, 4: 0}
print(c2.count)
# {0: 0, 1: 0, 2: 2, 3: 0, 4: 0}
del c1[1]
print(c1.count)
# {0: 0, 1: 0, 2: 0, 3: 0}
links = {'B': '百度', 'A': '阿里', 'T': '腾讯'}
for each in links:
print('%s -> %s' % (each, links[each]))
'''
B -> 百度
A -> 阿里
T -> 腾讯
'''
for each in iter(links):
print('%s -> %s' % (each, links[each]))
type(iter(links)) # dict_keyiterator
links = {'B': '百度', 'A': '阿里', 'T': '腾讯'}
it = iter(links)
print(next(it)) # B
print(next(it)) # A
print(next(it)) # T
print(next(it)) # StopIteration
it = iter(links)
while True:
try:
each = next(it)
except StopIteration:
break
print(each)
# B
# A
# T
把一个类作为一个迭代器使用需要在类中实现两个魔法方法 __iter__() 与 __next__() 。
class Fibs:
def __init__(self, n=10):
self.a = 0
self.b = 1
self.n = n
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if self.a > self.n:
raise StopIteration
return self.a
fibs = Fibs(100)
for each in fibs:
print(each, end=' ')
# 1 1 2 3 5 8 13 21 34 55 89
def myGen():
print('生成器执行!')
yield 1
yield 2
myG = myGen()
print(next(myG))
# 生成器执行!
# 1
print(next(myG)) # 2
print(next(myG)) # StopIteration
myG = myGen()
for each in myG:
print(each)
'''
生成器执行!
1
2
'''
# 用生成器实现斐波那契数列
def libs(n):
a = 0
b = 1
while True:
a, b = b, a + b
if a > n:
return
yield a
for each in libs(100):
print(each, end=' ')
# 1 1 2 3 5 8 13 21 34 55 89
利用python做一个简单的定时器类
要求:
# your code here