• Python面向对象之常用的特殊方法(5)


    Python面向对象里面有很多特殊方法,例如__init__(构造方法),__del__(析构方法),这些方法对于面向对象编程非常重要,下面列出一些常用的特殊方法

    (1)__call__

    class Foo:
        def __init__(self):
            self.name = 'name'
    
        def __call__(self, *args, **kwargs):
            print('call')
            return 1
    
    
    r = Foo()
    a=r()#实例后面加括号,执行类里面的__call__方法,也可以Foo()()来调用
    print(a)
    

      结果如图

    (2)__getitem__ 、__setitem__、__delitem__

    class Foo:
        def __init__(self):
            self.name = 'name'
        def __getitem__(self, item):
            print(item)
        def __setitem__(self, key, value):
            print(key,value)
        def __delitem__(self, key):
            print(key,'del')
    
    r = Foo()
    r['k1fdsfsdfs']#中括号里面加个值,调用时候默认执行__getitem__方法
    r['jay'] = 33 #这个的值,会在调用的时候执行__setitem__方法
    del r['xxxx']#这样会默认调用类里面的__delitem__方法
    

      执行结果如图

    如果是切片或者索引,都是执行这个方法,如图

    (3)__dict__

    查看类或者实例里面的所以属性或者方法

    class B():
        age = 23
        def __init__(self,name):
            self.name = name
        def bobn(self):
            print('B的方法')
        #super(B,self).__init__()
        #A.__init__(self)#执行父类的构造函数,把B的实例传进去
    b =B('jay')
    print(b.__dict__)#查看实例里面的方法或者属性
    print(B.__dict__)#查看类里面的方法或者属性
    

      结果如图

    (4)__doc__起注释作用

    如图

    (5)__iter__,在对象被for循坏时候自动调用

    class B():
        '我是类的注释'
        age = 23
        def __init__(self,name):
            self.name = name
        # def bobn(self):
        #     print('B的方法')
        def __iter__(self):#有yield,就是一个生成器
            yield 1
            yield 2
            yield 3
    
    obj = B('jay')
    for i in obj:#会默认执行类里面的iter方法,也就是一个对象可以被for循环,就是因为其内部有一个iter方法
        print(i)
    

      结果如图

  • 相关阅读:
    事务笔记
    MyBatis执行流程(面试题)
    mapper映射文件中 #{}与${}区别(面试题)
    前端内存泄露浅谈
    vue中使用element来创建目录列表
    vue中组件之间的传值
    nodejs+vue实现登录界面功能(二)
    nodejs+vue实现登录界面功能(一)
    threejs(一):初步认识与使用
    官网编辑遇到的各种问题记录(一)
  • 原文地址:https://www.cnblogs.com/xiaobeibei26/p/6438481.html
Copyright © 2020-2023  润新知