python常用内置函数

时间:2020-05-09
本文章向大家介绍python常用内置函数,主要包括python常用内置函数使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

常用魔法函数(非数学运算类型)

字符串表示

  • __repr__
  • __str__

集合序列相关

  • __len__
  • __getitem__
  • __setitem__
  • __delitem__
  • __contains__

迭代相关

  • __iter__
  • __next__

可调用

  • __call__

with上下文管理器

  • __enter__
  • __exit__

数值转换

  • __abs__
  • __bool__
  • __int__
  • __float__
  • __hash__
  • __index__

元类相关

  • __new__
  • __init__

属性相关

  • __getattr__
  • __setattr__
  • __getattribute__
  • __setattribute__
  • __dir__

属性描述符

  • __get__
  • __set__
  • __delete__

协程

  • __await__
  • __aiter__
  • __anext__
  • __aenter__
  • __aexit__

常用魔法函数(数学运算类型)

一元运算符

  • __neg__(-)
  • __pos__(+)
  • __abs__

二元运算符

  • __lt__(<)
  • __le__ <=
  • __eq__ ==
  • __ne__ !=
  • __gt__ >
  • __ge__ >=

算术运算符

  • __add__ +
  • __sub__ -
  • __mul__ *
  • __truediv__ /
  • __floordiv__ //
  • __mod__ %
  • __divmod__ 或 divmod()
  • __pow__ 或 ** 或 pow()
  • __round__ 或 round()

反向算术运算符

  • __radd__
  • __rsub__
  • __rmul__
  • __rtruediv__
  • __rfloordiv__
  • __rmod__
  • __rdivmod__
  • __rpow__

增量赋值算术运算符

  • __iadd__
  • __isub__
  • __imul__
  • __itruediv__
  • __ifloordiv__
  • __imod__
  • __ipow__

位运算符

  • __invert__ ~
  • __lshift__ <<
  • __rshift__ >>
  • __and__ &
  • __or__ |
  • __xor__ ^

反向位运算符

  • __rlshift__
  • __rrshift__
  • __rand__
  • __rxor__
  • __ror__

增量赋值位运算符

  • __ilshift__
  • __irshift__
  • __iand__
  • __ixor__
  • __ior__

调试工具

  • notebook

首先使用pip install -i https://douban.com/simple notebook安装然后运行ipython notebook

字符串表示

  • __str__

在打印一个实例化对象的时候, python默认会调用str(对象), 对应的魔法函数是__str__

class Company(object):
    def __init__(self, employee__list):
        self.employee = employee__list

company = Company(["tom", "bob", "jane"])
print(company)
print(str(company))

<__main__.Company object at 0x000001CFA60BE748>
<__main__.Company object at 0x000001CFA60BE748>
  • __repr__

__repr__是在开发模式下调用的

class Company(object):
    def __init__(self, employee__list):
        self.employee = employee__list

company = Company(["tom", "bob", "jane"])
print(company)
company

<__main__.Company object at 0x0000020A9D7672B0>
<__main__.Company at 0x20a9d7672b0>

再次强调, __repr__不是因为该类继承了某一个对象才能去写这个方法, 魔法函数可以写到任何一个定义的类中去, 然后python解释器就是识别出这个对象有该特性, 然后再调试模式下company会被解释器转换为repr(company), 然后再去调用company.__repr__().

class Company(object):
    def __init__(self, employee__list):
        self.employee = employee__list

    def __str__(self):
        return ','.join(self.employee)

    def __repr__(self):
        return '.'.join(self.employee)

company = Company(["tom", "bob", "jane"])
print(company) # str 输出
company        # repr输出

tom,bob,jane   # 打印对象
tom.bob.jane   # 调试模式

原文地址:https://www.cnblogs.com/wangbaojun/p/12858941.html