Python基础-定制类(str_iter_getItem_getattr_call)

来源:互联网 发布:杭州认知网络 招聘 编辑:程序博客网 时间:2024/05/29 04:31

str

让打印更加好看

示例

#!/usr/bin/env python3# -*- coding: utf-8 -*-# 定制类 __str__class Animal(object):    def __init__(self, name):        self.name = name    # 让打印更加好看    def __str__(self):        return "Animal' name is " + self.name;# 运行方法def runTest():    print(Animal("旺财"))# 运行runTest()

运行结果

D:\PythonProject>python main.pyAnimal' name is 小狗

iter

如果一个类想被用于for … in循环,类似list或tuple那样,就必须实现一个iter()方法,该方法返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的next()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环。

运行实例

#!/usr/bin/env python3# -*- coding: utf-8 -*-# 如果一个类想被用于for ... in循环,类似list或tuple那样,就必须实现一个__iter__()方法,该方法返回一个迭代对象,# 然后,Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环。class Count(object):    def __init__(self):        self.a = 0    def __iter__(self):        # 实例本身就是一个Iterator对象        return self    def __next__(self):        self.a = self.a + 1        if (self.a > 10):            raise StopIteration()        return self.a# 运行方法def runTest():    for n in Count():        print(n)# 运行runTest()

运行结果

D:\PythonProject>python main.py12345678910

getItem

取某一个子项,像List一样取值

运行实例

#!/usr/bin/env python3# -*- coding: utf-8 -*-# __getitem__class Count(object):    def __getitem__(self, a):        return a * a# 运行方法def runTest():    print(Count()[5])# 运行runTest()

运行结果

D:\PythonProject>python main.py25

getattr

自定义取不到属性的错误信息提示

示例

#!/usr/bin/env python3# -*- coding: utf-8 -*-# __getattr__class Count(object):    def __getattr__(self, attr):        return "自定义取不到属性的错误信息提示"# 运行方法def runTest():    print(Count().a)# 运行runTest()

运行结果

D:\PythonProject>python main.py自定义取不到属性的错误信息提示

call

任何类,只需要定义一个call()方法,就可以直接对实例进行调用

示例

#!/usr/bin/env python3# -*- coding: utf-8 -*-# 任何类,只需要定义一个__call__()方法,就可以直接对实例进行调用class Count(object):    def __call__(self):        print("任何类,只需要定义一个__call__()方法,就可以直接对实例进行调用") # 运行方法def runTest():    c = Count()    c()# 运行runTest()

运行结果

D:\PythonProject>python main.py任何类,只需要定义一个__call__()方法,就可以直接对实例进行调用
原创粉丝点击