• python的自省函数, 快速找出BUG的良器


    python内置的好多自省函数,  合理使用可快速查找相关提示, 快速找到问题点, 以下开始具体说明

    1. dir()  列出对象的所有属性和方法

      如:  dir(list)  可以列出列表的所有属性和方法

      ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',   '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__',   '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__',   '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert',   'pop', 'remove', 'reverse', 'sort']

    2. callable()  判断对象是否可以被调用

        callable() 函数用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象    ojbect绝对不会成功。对于函数, 方法, lambda 函式, 类, 以及实现了 __call__方法的类实例, 它都返回 True。

      语法:  callable(object)    object为对象 ,可调用返回true, 不可调用返回false

    3. isinstance()   判断某个变量是否具有某种类型

      语法: isinstance(object, classinfo)     object -- 实例对象, classinfo -- 可以是直接或间接类名、基本类型或者由它们组成的元组

      如果object是classinfo的实例, 或者object是classinfo类的子类的一个实例, 则返回true, 否则返回false

      举例:  isinstance(4, int)  返回true

         isinstnace(4, (string, float, int))   4 是元组(string, float, int) 中的一种, 也会返回true

    4. hasatter() 和getattr()  判断对象是否有某个属性及获取属性

      语法:    hasattr(object, name)    getattr(object, name [, default])

      举例说明:

      class Demo(object):

        def __init__(self):

          self.name = "laowang"

        def make(self):

          print('OK')

      a = Demo()

      print(hasattr(a, "name"))           实例化的 对象a具有name属性, 则返回true, 没有则返回false

      print(getattr(a, "age", 18))         实例化的对象a不具有age属性, 则会返回后面的18, 如果不指定18, 则报错

    5. help()   查看python的帮助文档

      不确定怎么使用某个内置方法可以使用help()查看

      如  help(print), 会返回print()的详细使用方式, 后面的flush参数你真的懂吗?

      Help on built-in function print in module builtins:
    
      print(...)
          print(value, ..., sep=' ', end='
    ', file=sys.stdout, flush=False)
    
          Prints the values to a stream, or to sys.stdout by default.
          Optional keyword arguments:
          file:  a file-like object (stream); defaults to the current sys.stdout.
          sep:   string inserted between values, default a space.
          end:   string appended after the last value, default a newline.
          flush: whether to forcibly flush the stream.

    6.  其余的经常使用的还包括

      type()   返回对象的类型

      id()   返回对象的引用地址, 类似于 is , 可以查看两个变量的内存地址是否一样  

  • 相关阅读:
    指针+[][]T 类型
    linux适用小工具-tmux
    wrk+lua进行压力测试
    brew更换为国内源
    k8s证书更新
    ssh隧道
    kubeadm安装集群系列(kubeadm 1.15.1)
    harbor清理存储
    第十周课程总结
    第九周课程总结&第七次实验报告
  • 原文地址:https://www.cnblogs.com/skaarl/p/9692073.html
Copyright © 2020-2023  润新知