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) 大于等于 >= 
复制代码

 

posted @   杨灏  阅读(212)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
历史上的今天:
2018-08-20 jenkins忘记登录密码解决方法
点击右上角即可分享
微信分享提示