• python魔术方法- __init__,_new_,_call_,_str_,_repr_,_add_,_getitem_,_getattr_,_bases_,_dict_,_slots_


     __init__ 和 __new__的区别

    # __new__ : 创建对象  Create and return a new object.
    # __init__ : 初始化对象
    
    class MyClass(object):
        def __init__(self):
            print("init is running ...")
    
        def __new__(cls, *args, **kwargs):
            # 创建对象
            # 分配内存
            print("new is running ...")
            obj = super().__new__(cls)  # 创建对象
            return obj

    __call__方法

    实现一个对象像函数一样被调用

    例如函数自带call属性,能够直接调用:add(1,2)

    def add(x, y):
        return x + y
    
    print(dir(add))
    
    结果:
    ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

    __str__方法

    print(obj)原来返回的是一个对象,现在用str方法可以自定义一个返回值,print的时候打印返回的值

    class MyClass(object):
        def __init__(self, name):
            self.name = name
    
        def __str__(self):
            print("---str is running---")
            return self.name
            # return '1'
    
    
    def main():
        obj = MyClass('马师傅')
        print(hasattr(obj, '__str__'))
        # 以下三种方式可以触发__str__
        print(obj) # return self.name返回 马师傅;return '1'返回 1
        str(obj)
        format(obj)
    
    
    if __name__ == '__main__':
        main()
    
    
    结果:
    True
    ---str is running---
    马师傅
    ---str is running---
    ---str is running---

    __repr__方法

    如果没有__str__方法,就会触发__repr___

    class MyClass(object):
        def __init__(self, name):
            self.name = name
    
        # def __str__(self):
        #     print("---str is running---")
        #     return self.name
        #     # return '1'
    
        def __repr__(self):
            print("---repr is running---")
            return self.name
            # return '1'
    
    def main():
        obj = MyClass('马师傅')
        print(hasattr(obj, '__str__'))
        # 以下三种方式可以触发__str__
        print(obj) # return self.name返回 马师傅;return '1'返回 1
        str(obj)
        format(obj)
    
    
    if __name__ == '__main__':
        main()
    
    
    结果:
    True
    ---repr is running---
    马师傅
    ---repr is running---
    ---repr is running---

     

    __add__方法

    class MyClass(object):
    
        def __init__(self, value):
            self.value = value
    
        def __add__(self, other):
            return self.value + other.value
    
    
    def main():
        a = [1, 2]
        b = [3, 4]
        print(a + b)
        obj1 = MyClass(10.00)
        obj2 = MyClass(11.00)
        print(obj1 + obj2)
        print(hasattr(a, '__add__'))
    
    
    if __name__ == '__main__':
        main()
    
    
    结果:
    [1, 2, 3, 4]
    21.0
    True

    __getitem__方法

    有__getitem__方法的对象才能用[]操作

    class MyClass(object):
        def __init__(self):
            self.items = ['a', 'b', 'c']
    
        # 有__getitem__方法的对象才能用[]操作
        def __getitem__(self, i):
            return self.items[i]
    
    
    if __name__ == '__main__':
        obj = MyClass()
        print(obj[0])  # a
        print(obj[1])  # b
        print(obj[2])  # c
        print(hasattr(tuple, '__getitem__'))  # True
        print(hasattr(1, '__getitem__'))  # False
        print(hasattr(dict, '__getitem__'))  # True
    
        print({'name': 'xxx'}['name'])
    
    
    结果:
    a
    b
    c
    True
    False
    True
    xxx

    __getattr__方法

    class MyClass:
    
        def __init__(self,name):
            self.name = name
    
        # __getattr__ 当获得对象的属性,而对象无此属性时执行
        def __getattr__(self, item):
            return 999
    
    myclass = MyClass("Tom")
    print(myclass.name)
    print(myclass.age)
            
    
    结果:
    Tom
    999

    __bases__方法

    __bases__: 就是一个元组,里面是继承的类
    class A(object):
        pass
    
    
    class B(object):
        pass
    
    
    class MyClass(A, B):
        pass
    
    
    if __name__ == '__main__':
        print(MyClass.__bases__)
    
    # __bases__: 就是一个元组,里面是继承的类
    
    结果:
    (<class '__main__.A'>, <class '__main__.B'>)

    __dict__方法

    __dict__方法可以把属性取出来

    类取出类的属性,对象取出对象的属性

    class MyClass(object):  # MyClass 是类 , 类 其实就是 定义如何创建对象的一段代码
        a = 0  # 类变量 (归属于类)
    
        def __init__(self, name, age):
            temp = 1  # 局部变量
            self.name = name  # self  是对象
            self.age = age  # name ,age  实例变量(归属于对象)
    
        def get_name(self):
            return self.name
    
    
    if __name__ == '__main__':
        obj = MyClass('Tom', 100)
        print(MyClass.__dict__)
        print(obj.__dict__)
    
    
    结果:
    {'__module__': '__main__', 'a': 0, '__init__': <function MyClass.__init__ at 0x00000213456FF940>, 'get_name': <function MyClass.get_name at 0x00000213456FFC10>, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None}
    {'name': 'Tom', 'age': 100}

    __slots__方法

    魔术方法大全:https://www.cnblogs.com/nmb-musen/p/10861536.html

  • 相关阅读:
    awk: 两列相加
    awk: 多行转一行(一列转一行)并在加上双引号和逗号
    R也可以计算保守性得分(phastCons100way.UCSC.hg19)
    linux:提取列数一致的行
    本周最新文献速递20210509
    菠萝蜜成长记
    报错:UnavailableInvalidChannel: The channel is not accessible or is invalid解决方法
    awk无法比较数值
    【专利自助申请指引 ● 第1章. 申请流程介绍 ● 1.2.6 完成费减备案(可选)】
    【专利自助申请指引 ● 第1章. 申请流程介绍 ● 1.2.5 提前公布请求和实质审查请求】
  • 原文地址:https://www.cnblogs.com/erchun/p/14083211.html
Copyright © 2020-2023  润新知