功能点
多重继承
定制类
getattr
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Fib实例虽然能作用于for循环,看起来和list有点像,但是,把它当成list来使用还是不行
class Student(object):
def __init__(self):
self.name = 'tan'
def __getattr__(self, item):
if item == 'score':
return 99
else:
return '其他'
s = Student()
print(s.name) # tan
print(s.a) # 其他
print(s.score) # 99
复制代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Fib实例虽然能作用于for循环,看起来和list有点像,但是,把它当成list来使用还是不行
class Student(object):
def __init__(self, name):
self.name = 'tan'
def __call__(self, *args, **kwargs):
print('my name is %s.' % self.name)
s = Student('tan')
s()
# 通过callable()函数,我们就可以判断一个对象是否是“可调用”对象
print(callable(Student('aa')))
print(callable(max))
print(callable([1, 2, 3, 4]))
print(callable(None))
print(callable('str'))
复制代码
getitem
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Fib实例虽然能作用于for循环,看起来和list有点像,但是,把它当成list来使用还是不行
class Fib(object):
def __init__(self):
self.a, self.b = 0,5
def __iter__(self):
return self # 实例本身就是迭代对象,返回自己
def __next__(self):
self.a, self.b = self.b, self.a + self.b # 计算下一个值
if self.a > 1000:
raise StopIteration()
return self.a
# Fib当list处理,需加方法
def __getitem__(self, item):
a, b = 1, 1
for x in range(item):
a, b = b, a+b
return a
def __getitem__(self, n):
if isinstance(n, int): # n是索引
a, b = 1, 1
for x in range(n):
a, b = b, a + b
return a
if isinstance(n, slice): # n是切片
start = n.start
stop = n.stop
if start is None:
start = 0
a, b = 1, 1
L = []
for x in range(stop):
if x >= start:
L.append(a)
a, b = b, a + b
return L
print(Fib()[5]) # Fib实例当list处理 报错 TypeError: 'Fib' object is not subscriptable 加__getitem__方法转list
for n in Fib():
print(n)
print(Fib()[1:5])
# 延伸 __setitem__ __delitem__
复制代码
iternext
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Fib(object):
def __init__(self):
self.a, self.b = 0,1
def __iter__(self):
return self # 实例本身就是迭代对象,返回自己
def __next__(self):
self.a, self.b = self.b, self.a + self.b # 计算下一个值
if self.a > 1000:
raise StopIteration()
return self.a
for n in Fib():
print(n)
# a 1 b 1
# a 1 b 2
# a 2 b 3
# a 3 b 5
# a 5 b 8
# a 8 b 13
复制代码
repr
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object (name: %s)' % self.name
__repr__ = __str__
s = Student('tan')
print(s) # Student object (name: tan)
复制代码
str
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object (name: %s)' % self.name
print(Student('tan')) # 没有__str__ 打印 <__main__.Student object at 0x000001C382494C70> 有str 打印Student object (name: tan)