python 特殊方法

python 特殊方法

  1. 简介

    1
    2
    3
    4
    5
    * python 中一切皆对象
    * 特殊方法:
    1.以双下划线开头,并以双下划线结尾
    2.__方法名__,例如: __init__
    3.可以通过dir()查看
  2. 实例操作

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    //查看特殊方法
    >>> dir(list)
    ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

    //运算符(对象.特殊方法)
    >>> 'nihao' + 'beijing'
    'nihaobeijing'
    >>> 'nihao'.__add__('beijing')
    'nihaobeijing'

    >>> 1.1 * 8
    8.8
    >>> 1.1.__mul__(8)
    8.8

    //列表(对象.特殊方法)
    >>> a = [1,2,3,4]
    >>> len(a)
    4
    >>> a.__len__()
    4

    >>> a[3]
    4
    >>> a.__getitem__(3)
    4

    >>> a[0] = 9
    >>> a
    [9, 2, 3, 4]
    >>> a.__setitem__(0,10)
    >>> a
    [10, 2, 3, 4]

    //函数
    >>> class A(object):
    ... def __call__(self,a):
    ... return a + 10
    ...
    >>> b = A()
    >>> print(b(1))
    11

    >>> map(b,[1,2,3,4,5])
    [11, 12, 13, 14, 15]