zoukankan      html  css  js  c++  java
  • python 面向对象(类的特殊成员)

    python 面向对象:

    (思维导图 ↑↑↑↑)

    类的特殊成员

      python的类成员存在着一些具有特殊含义的成员

    1.__init__: 类名() 自动执行 __init__

    class Foo(object):
    
        def __init__(self,a1,a2):
            self.a1 = a1
            self.a2 = a2
    
    obj = Foo(1,2)

    2.__call__: 对象() 自动执行__call__

    class Foo(object):
    
        def __call__(self, *args, **kwargs):
            print(1111,args,kwargs)
            return 123
    
    obj = Foo()
    ret = obj(6,4,2,k1=456)

    3.__getitem__: 对象['xx'] 自动执行__getitem__

    class Foo(object):
    
        def __getitem__(self, item):
            print(item)
            return 8
    obj = Foo()
    ret = obj['yu']
    print(ret)

    4.__setitem__: 对象['xx'] = 11 自动执行__setitem__

    class Foo(object):
    
        def __setitem__(self, key, value):
            print(key, value, 111111111)
    obj = Foo()
    obj['k1'] = 123

    5.__delitem__: del 对象[xx] 自动执行__delitem__

    class Foo(object):
    
        def __delitem__(self, key):
            print(key)
    obj = Foo()
    del obj['uuu']

    6.__add__: 对象+对象 自动执行__add__

    class Foo(object):
        def __init__(self, a1, a2):
            self.a1 = a1
            self.a2 = a2
        def __add__(self,other):
            return self.a1 + other.a2
    obj1 = Foo(1,2)
    obj2 = Foo(88,99)
    ret = obj2 + obj1
    print(ret)

    7.__enter__ / __exit__: with 对象 自动执行__enter__ / __exit__

    class Foo(object):
        def __init__(self, a1, a2):
            self.a1 = a1
            self.a2 = a2
        def __enter__(self):
            print('1111')
            return 999
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            print('22222')
    obj = Foo(1,2)
    with obj as f:
        print(f)
        print('内部代码')

    8.__new__: 构造方法

    class Foo(object):
        def __init__(self, a1, a2):     # 初始化方法
            """
            为空对象进行数据初始化
            :param a1:
            :param a2:
            """
            self.a1 = a1
            self.a2 = a2
    
        def __new__(cls, *args, **kwargs): # 构造方法
            """
            创建一个空对象
            :param args:
            :param kwargs:
            :return:
            """
            return object.__new__(cls) # Python内部创建一个当前类的对象(初创时内部是空的.).
    
    obj1 = Foo(1,2)
    print(obj1)
    
    obj2 = Foo(11,12)
    print(obj2)
  • 相关阅读:
    C++ 资源大全中文版
    C++标准库和标准模板库
    非常实用全面的 C++框架,库类等资源
    Parse陨落,开发者服务今后路在何方?
    MySQL 创始人:写代码比打游戏爽,程序员应多泡开源社区
    用callgraph生成的函数调用关系图
    Qemu对x86静态内存布局的模拟
    几篇QEMU/KVM代码分析文章
    任务执行引擎的工程
    初涉核心域
  • 原文地址:https://www.cnblogs.com/zbw582922417/p/9554912.html
Copyright © 2011-2022 走看看