zoukankan      html  css  js  c++  java
  • python类的内置方法

    1.python 类的内置方法

    1.__new__:    在__init__触发前自动触发

    2.__init__: 在调用类产生对象时触发

    3.__getattr__: 在使用“对象.属性” 获取属性,属性不存在时,自动触发

    4.__getattribute__: 在使用‘对象.属性’获取属性,无论属性有没有,都会自动触发

    5.__setattr__: 在使用“对象.属性 = 属性值”,添加或修改属性值时触发

    6.__call__: 在使用 “对象 +()” 时,触发

    7.__str__: 在打印对象时触发

    8.__getitem__: 在通过 对象[key] 获取对象属性时触发

    9.__setitem__: 在通过 对象[key] = value 设置属性值时触发

    10.__del__: 删除对象时触发(del obj),或者python解释器运行完py文件 回收(删除)对象时触发

    实例:

    class Demo(object):
        # 条件:__new__:在__init__触发之前,自动触发触发
        def __new__(cls, *args, **kwargs):  # 这里相当于重写了__new__的方法
            print('此处__new__方法的执行')
            return object.__new__(cls, *args, **kwargs)
    
        def __init__(self):
            print("此处__init__方法的执行")
    
        # demo_obj = Demo()
    
        # 条件:在在 “对象.属性” 获取属性时,若 “属性没有” 时触发。
        def __getattr__(self, item):
            print('此处__getattr__方法的执行')
            print(item)
    
        # demo_obj = Demo()
        # print(demo_obj.__dict__)
    
        # 注意: 只要__getattr__ 与 __getattribute__ 同时存在类的内部,只会触发__getattribute__。
        # 条件: __getattribute__: 在 “对象.属性” 获取属性时,无论"属性有没有"都会触发
        def __getattribute__(self, item):
            print("此处是__getatribute__的执行")
    
            # return object.__getattribute__(self, item)
    
        # demo_obj = Demo()
        # demo_obj.x()
    
        # 条件: 当 “对象.属性 = 属性值” , 添加或修改属性时触发
        def __setattr__(self, key, value):
            print("此处是__setattr__的执行")
            print(key, value)
    
        # demo_obj = Demo()
        # demo_obj.x = 10
    
        # 条件: 在调用对象 “对象 + ()” 时触发。
        def __call__(self, *args, **kwargs):
            print("此处是__call__的执行")
    
        # demo_obj = Demo()
        # demo_obj()
    
        # 条件: 在打印"对象"时触发。
        # 注意: 该方法必须要有一个 “字符串” 返回值
        def __str__(self):
            print("此处是__str__的执行")
            return '111'
    
        # demo_obj = Demo()
        # # print(demo_obj)
    
        # 在对象通过 “对象[key]” 获取属性时触发。
        def __getitem__(self, item):
            print("此处是__getitem__的执行")
    
        # demo_obj = Demo()
        # print(demo_obj['x'])
    
        # 在对象通过 “对象[key]=value值” 设置属性时触发
        def __setitem__(self, key, value):
            print('此处是__setitem__方法的执行')
    
    
    demo_obj = Demo()
    demo_obj['x'] = 111
    print(demo_obj.x)
  • 相关阅读:
    gbin1分享: jQuery UI 1.9带给我们的惊喜
    7个优秀的javascript资源
    转载:仅需78美元,你就能拥有一个iPhone机器人Romo
    GBin1推荐:使用时间轴插件Timelinr创建超酷jQuery时间轴(Time line)
    GBin1分享:10个帮助你精通Firebug控制台的技巧
    GBin1分享:jQuery1.7 Beta 预览
    批处理文件安装卸载window服务程序的技巧
    当前不会命中断点 还没有为该文档加载任何符号
    HttpModule,HttpHandler,HttpHandlerFactory简单使用
    VS2010 .net Windows服务程序 重复性 注册反注册
  • 原文地址:https://www.cnblogs.com/bigbox/p/11960989.html
Copyright © 2011-2022 走看看