zoukankan      html  css  js  c++  java
  • python 常见的特殊方法

    特殊方法

    特殊方法,也称为魔术方法

    特殊方法都是使用__开头和结尾的

    class Foo(object):
        def __call__(self, *args, **kwargs):
            '''构造方法的执行是由创建对象触发的,对象加括号执行'''
            print('__call__方法执行了')
            return args, kwargs
    
        def __init__(self):
            '''构造方法,创建实例时候会自动执行,面向对象中非常常用,一般用来封装各种参数'''
            print('__init__执行了')
            self.data_dict = {'name': 'yanghao', 'age': 23}
    
        def __repr__(self):
            '''如果一个类中定义了__repr__方法,那么在repr(对象) 时,默认输出该方法的返回值。'''
            return '__repr__ 执行了'
    
        def __getitem__(self, key):
            '''获取值'''
            return print(self.data_dict[key])
    
        def __setitem__(self, key, value):
            '''设置值'''
            self.data_dict[key] = value
            return print(self.data_dict)
    
        def __delitem__(self, key):
            '''删除值'''
            self.data_dict.pop(key)
            return print(self.data_dict)
    
        def __getattr__(self, item):
            '''访问不存在的属性会调用'''
            print('__getattr__执行了')
    
        def __setattr__(self, key, value):
            '''设置属性'''
            print('__setattr__执行了')
            self.__dict__.setdefault(key, value)
            print(self.data_dict)
    
        def __delattr__(self, item):
            '''del obj.key'''
            print('执行 __delattr__')
            print(self.__dict__)
            self.__dict__.pop(item)
    
        def __len__(self):
            '''len'''
            return len(self.data_dict)
    
        def __str__(self):
            '''如果类中有str方法的话直接打印实例,会输出str方法中定义的返回内容'''
            return '__str__执行了'
    
        def __del__(self):
            '''析构方法,当对象在内存中被释放时,自动触发执行。'''
            print('__del__释放')
    
    
    class Aoo(object):
    
        def __init__(self):
            self.x = 1
    
            print('in init function')
    
        def __new__(cls, *args, **kwargs):
            '''new方法和init方法的区别就是,new方法是正在创建实例时候执行,而init方法是创建实例后才执行。'''
            print('in new function')
    
            return object.__new__(Aoo, *args, **kwargs)
    
    
    if __name__ == '__main__':
        obj = Foo()
        # ------------------------------
        obj()  # __call__
        print(repr(obj))
        a = obj['name']
        obj['phone'] = 18577609987
        del obj['age']
        # -------------------------------
        print('-' * 80)
        # ------------操作对象属性-------------------
        getattr(obj, 'dsadasda')  # 不存在的属性时会调用该方法,你可返回任何值,当找不到时便返回。
        setattr(obj, 'a1', '123')
        del obj.data_dict
        # -------------------------------
        print('-' * 80)
        # -------------------------------
        print(len(obj()))
        print(obj)
        # -------------------------------
        a_obj = Aoo()
    
        print(a_obj.x)

    除了上面部分还有下面这些特殊方法也都是比较实用的

        # __add__(self, other)
        # __sub__(self, other)
        # __mul__(self, other)
        # __matmul__(self, other)
        # __truediv__(self, other)
        # __floordiv__(self, other)
        # __mod__(self, other)
        # __divmod__(self, other)
        # __pow__(self, other[, modulo])
        # __lshift__(self, other)
        # __rshift__(self, other)
        # __and__(self, other)
        # __xor__(self, other)
        # __or__(self, other)
    
        # __lt__(self, other) 小于 <
        # __le__(self, other) 小于等于 <=
        # __eq__(self, other) 等于 ==
        # __ne__(self, other) 不等于 !=
        # __gt__(self, other) 大于 >
        # __ge__(self, other) 大于等于 >= 
  • 相关阅读:
    centos7 常用工具包安装
    Java.lang.String类
    javaweb系统调优方案
    nginx 优化
    centos7 源码安装nginx
    tomcat8调优
    commons-logging slf4j log4j 区别
    docker 安装centos7并SSH远程连接
    aws mysql 开启慢查询日志, 并利用mysqlsla 分析
    centos7 源码安装goaccess
  • 原文地址:https://www.cnblogs.com/HByang/p/13534573.html
Copyright © 2011-2022 走看看