# !/usr/bin/env python3
# -*- coding: utf-8 -*-
'根据自己的需求定制特殊的类'
__author__ = 'zhaohe'
class Fib2(object):
"""docstring for Fib2"""
def __init__(self, name):
self.name = name
self['k1'] = '2k'
self['k2'] = '3k'
del self['k2']
self.a, self.b = 0, 1
def __str__(self): # __str__ 与 __repr__使类的打印更漂亮
return 'Fib object (name: %s)' % self.name
__repr__ = __str__
def __iter__(self): # __iter__ 返回一个可迭代对象
return self # 实例本身就是迭代对象,故返回自己
def __next__(self): # 不断调用可迭代对象(由 __iter__ 返回)
self.a, self.b = self.b, self.a + self.b
if self.a > 1000000:
raise StopIteration()
return self.a
# 访问不存在的属性时会调用 __getitem__
def __getitem__(self, item): # 可实现列表打印、切片
if isinstance(item, int):
m, n = 1, 1
for x in range(item):
m, n = n, m + n
return m
if isinstance(item, slice):
start = item.start
stop = item.stop
if start == 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
# 每当属性被赋值时会调用 __setitem__
def __setitem__(self, key, value):
print('__setitem__:Set %s Value %s' % (key, value))
self.__dict__[key] = value
# 删除属性时调用 __delitem__
def __delitem__(self, key):
print('__delitem__: Delete attribute %s' % key)
del self.__dict__[key]
print(self.__dict__)
# 调用不存在的属性时会调用 __getattr__
def __getattr__(self, attr):
if attr == 'score':
return 99
if attr == 'age':
return lambda: 25
# 如果任意调用 如 f.qq 都会返回 None,
# 这是因为 __getattr 的默认返回值是 None
# 为响应不存在的属性,需要抛出属性错误
raise AttributeError('\'Student\' has no atribute \'%s\' ' % attr)
# 利用 __call__ 可直接对 实例和类 本身进行调用
def __call__(self):
print('My name is %s' % self.name)
print('My name is %s' % self)
# for i in Fib2('zhaohe'):
# print(i)
f = Fib2('zhaohe')
f()
print(f)
# print(f[226])
# print(f[10:15])
# print(f.name)
# print(f.score)
# print(f.qq)
print('Fib2 is callable?', callable(Fib2))