python定制类详解
1.什么是定制类
python中包含很多内置的(Built-in)函数,异常,对象。
分别有不同的作用,我们可以重写这些功能。
2.__str__
输出对象
class Language(object): def __init__(self): self.name = 'Python' print(Language())
运行结果:
class Language(object): def __init__(self): self.name = 'Python' def __str__(self): return "Language():%s"%(self.name) print(Language())
运行结果:
3.__iter__
遍历对象
class Language(object): def __init__(self): self.name = 'Python' self.count = 0 def __iter__(self): return self def __next__(self): self.count += 1 if self.count > 5: raise StopIteration() return self.count language = Language() for i in language: print(i)
运行结果:
__iter__返回的是迭代对象language
for..in..会自动调用__iter__迭代对象的__next__方法,直到__next__方法返回StopIteration异常。
4.__getitem__
定义了__getitem__方法后才能使用索引取值
class Language(object): def __getitem__(self, item): return item language = Language() print(language[0])
运行结果:
5.__getattr__
没有找到属性时,才会调用__getattr__
class Language(object): def __init__(self): self.name = 'Python' def __getattr__(self, item): if item == 'score': return 9 elif item == 'rank': return lambda :5 language = Language() print(language.score) print(language.rank())
运行结果:
6.__call__
对象可执行
class Language(object): def __init__(self): self.name = 'Python' def __call__(self, *args, **kwargs): print('My name is %s'%self.name) language = Language() language()
运行结果: