IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> Python:如何查看一个对象有哪些属性、方法以及查询源码中只有pass的方法的参数 -> 正文阅读

[Python知识库]Python:如何查看一个对象有哪些属性、方法以及查询源码中只有pass的方法的参数

作者:token keyword

1.问题背景

pythonC语言实现的,尽管有很多标准库是由python代码实现,但是涉及到底层支撑架构的功能或需要较高计算性能的实现还是会使用C语言。一些IDE为了对这些进行友好代码提示,会弄和底层一样的访问接口,而其实现直接过程写 pass 略过。
我们如果要查看某些功能的源码时,往往会发现这个方法上面只写了一个pass,并带有标识# real signature unknown; restored from __doc__,连可输入的参数有哪些都不知道:
在这里插入图片描述
上面的**kwargs表示关键字参数,如果是比较详细的库还好,会给你列出能输入哪些关键字参数,但大多数情况时你压根不知道可以输入的关键字参数有哪些~~

2.解决思路

2.1.查看对象有哪些属性或方法

这里我们以典型的计算库:numpy进行举例,因为其中含有大量C写的代码,而我们无法通过python查看其源代码:
在这里插入图片描述
在这里,初始化了一个ndarraya,然后对它排序,那么如何知道a有哪些方法能够调用呢?

2.1.1dir()函数

我们可以使用python自带的内置函数dir直接返回模块内定义的所有名称,结果以一个字符串列表的形式返回。:

dir(a)

可以看到得到了a能够调用的所有方法:

[‘T’, ‘abs’, ‘add’, ‘and’, ‘array’,
array_finalize’, ‘array_function’, ‘array_interface’,
array_prepare’, ‘array_priority’, ‘array_struct’,
array_ufunc’, ‘array_wrap’, ‘bool’, ‘class’,
complex’, ‘contains’, ‘copy’, ‘deepcopy’,
delattr’, ‘delitem’, ‘dir’, ‘divmod’, ‘doc’,
eq’, ‘float’, ‘floordiv’, ‘format’, ‘ge’,
getattribute’, ‘getitem’, ‘gt’, ‘hash’,
iadd’, ‘iand’, ‘ifloordiv’, ‘ilshift’,
imatmul’, ‘imod’, ‘imul’, ‘index’, ‘init’,
init_subclass’, ‘int’, ‘invert’, ‘ior’,
ipow’, ‘irshift’, ‘isub’, ‘iter’, ‘itruediv’,
ixor’, ‘le’, ‘len’, ‘lshift’, ‘lt’,
matmul’, ‘mod’, ‘mul’, ‘ne’, ‘neg’,
new’, ‘or’, ‘pos’, ‘pow’, ‘radd’,
rand’, ‘rdivmod’, ‘reduce’, ‘reduce_ex’,
repr’, ‘rfloordiv’, ‘rlshift’, ‘rmatmul’,
rmod’, ‘rmul’, ‘ror’, ‘rpow’, ‘rrshift’,
rshift’, ‘rsub’, ‘rtruediv’, ‘rxor’,
setattr’, ‘setitem’, ‘setstate’, ‘sizeof’,
str’, ‘sub’, ‘subclasshook’, ‘truediv’,
xor’, ‘all’, ‘any’, ‘argmax’, ‘argmin’, ‘argpartition’,
‘argsort’, ‘astype’, ‘base’, ‘byteswap’, ‘choose’, ‘clip’,
‘compress’, ‘conj’, ‘conjugate’, ‘copy’, ‘ctypes’, ‘cumprod’,
‘cumsum’, ‘data’, ‘diagonal’, ‘dot’, ‘dtype’, ‘dump’, ‘dumps’,
‘fill’, ‘flags’, ‘flat’, ‘flatten’, ‘getfield’, ‘imag’, ‘item’,
‘itemset’, ‘itemsize’, ‘max’, ‘mean’, ‘min’, ‘nbytes’, ‘ndim’,
‘newbyteorder’, ‘nonzero’, ‘partition’, ‘prod’, ‘ptp’, ‘put’,
‘ravel’, ‘real’, ‘repeat’, ‘reshape’, ‘resize’, ‘round’,
‘searchsorted’, ‘setfield’, ‘setflags’, ‘shape’, ‘size’, ‘sort’,
‘squeeze’, ‘std’, ‘strides’, ‘sum’, ‘swapaxes’, ‘take’,
‘tobytes’, ‘tofile’, ‘tolist’, ‘tostring’, ‘trace’, ‘transpose’,
‘var’, ‘view’]

2.1.2.help命令

如果我们需要更详细的解释,可以对a使用help命令,该命令会返回对象的完整帮助文档(由于文档实在太长,只截取了一部分):

help(a)

Help on ndarray object:
class ndarray(builtins.object)
| ndarray(shape, dtype=float, buffer=None, offset=0,
| strides=None, order=None)
|
| An array object represents a multidimensional, homogeneous array
| of fixed-size items. An associated data-type object describes the
| format of each element in the array (its byte-order, how many bytes it
| occupies in memory, whether it is an integer, a floating point number,
| or something else, etc.)
|
| Arrays should be constructed using array, zeros or empty (refer
| to the See Also section below). The parameters given here refer to
| a low-level method (ndarray(...)) for instantiating an array.
|
| For more information, refer to the numpy module and examine the
| methods and attributes of an array.
|

Parameters
(for the new method; see Notes below)
shape : tuple of ints
Shape of created array.
dtype : data-type, optional
Any object that can be interpreted as a numpy data type.
buffer : object exposing buffer interface, optional
Used to fill the array with data.
offset : int, optional

2.2.查看方法的参数有哪些?

2.2.1.inspect模块

这个模块可以查看可以查看函数的代码,参数,以及路径:

  • 查看函数的路径 inspect.getabsfile(…)
  • 查看全部代码 inspect.getsource(模块.函数)或者(模块.类.函数)
  • 查看函数参数 inspect.getfullargspec(…) 查看类的参数,则括号里为(模块.类._init _)
'''
===========================================
  @author:  jayce
  @file:    inspect_args.py
  @time:    2022/4/20   18:42 
===========================================
'''
import numpy as np
import inspect


def inspect_args(num1, num2):
    '''
    :param num1:
    :param num2:
    :return:
    '''
    return num1 + num2


a = np.asarray([4, 5, 1, 2, 3])

# 查看函数路径:
print('查看函数路径:\n{}'.format(inspect.getabsfile(inspect_args)))
# 查看函数完整代码:
print('查看函数完整代码:\n{}'.format(inspect.getsource(inspect_args)))
# 查看函数有哪些参数:
print('查看函数有哪些参数:\n{}'.format(inspect.getfullargspec(inspect_args)))


可以看到inspect_args函数的相关信息被完整展示了出来:

查看函数路径:
e:\code\python\demo代码\inspect_args.py
查看函数完整代码:
def inspect_args(num1, num2):
    '''
    :param num1:
    :param num2:
    :return:
    '''
    return num1 + num2
查看函数有哪些参数:
FullArgSpec(args=['num1', 'num2'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={})

这里面需要重点关注的是getfullargspec,他返回了函数的具体参数,如下:

  • args:是位置参数名称的列表
  • varargs:是*参数的名称,None表示不接受任意位置参数
  • varkw:是**参数的名称,None表示不接受任意的关键字参数。
  • defaults:是与n个位置参数相对应的默认参数值的n元组,None表示没有默认值
  • kwonlyargs:是关键字参数名称的列表。
  • kwonlydefaults:是一个映射到kwonlyargs参数默认值字典,None表示没有
  • annotations:是将参数名称映射到注释的字典。该特殊键返回用于报告函数返回值注释(如果有的话)

但需要注意的是,getfullargspec只能查询由python编写的代码,如果查询其他语言写的代码,会报错:TypeError: unsupported callable

Traceback (most recent call last):
  File "C:\Users\Jayce\Anaconda3\envs\tf1.7\lib\inspect.py", line 1116, in getfullargspec
    sigcls=Signature)
  File "C:\Users\Jayce\Anaconda3\envs\tf1.7\lib\inspect.py", line 2183, in _signature_from_callable
    raise TypeError('{!r} is not a callable object'.format(obj))
TypeError: array([4, 5, 1, 2, 3]) is not a callable object
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "C:\Users\Jayce\Anaconda3\envs\tf1.7\lib\site-packages\IPython\core\interactiveshell.py", line 3343, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-3-6fd2d9db0386>", line 1, in <module>
    inspect.getfullargspec(a)
  File "C:\Users\Jayce\Anaconda3\envs\tf1.7\lib\inspect.py", line 1122, in getfullargspec
    raise TypeError('unsupported callable') from ex
TypeError: unsupported callable

2.2.2.help命令

help命令当然也可以查询函数的参数,如我们查询numpy.sum的参数有哪些:

>>>help(np.sum)
Help on function sum in module numpy:
sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
    Sum of array elements over a given axis.
    
    Parameters
    ----------
    a : array_like
        Elements to sum.
    axis : None or int or tuple of ints, optional
        Axis or axes along which a sum is performed.  The default,
        axis=None, will sum all of the elements of the input array.  If
        axis is negative it counts from the last to the first axis.
    
        .. versionadded:: 1.7.0
    
        If axis is a tuple of ints, a sum is performed on all of the axes
        specified in the tuple instead of a single axis or all the axes as
        before.
    dtype : dtype, optional
        The type of the returned array and of the accumulator in which the
        elements are summed.  The dtype of `a` is used by default unless `a`
        has an integer dtype of less precision than the default platform
        integer.  In that case, if `a` is signed then the platform integer
        is used while if `a` is unsigned then an unsigned integer of the
        same precision as the platform integer is used.
    out : ndarray, optional
        Alternative output array in which to place the result. It must have
        the same shape as the expected output, but the type of the output
        values will be cast if necessary.
    keepdims : bool, optional
        If this is set to True, the axes which are reduced are left
        in the result as dimensions with size one. With this option,
        the result will broadcast correctly against the input array.
    
        If the default value is passed, then `keepdims` will not be
        passed through to the `sum` method of sub-classes of
        `ndarray`, however any non-default value will be.  If the
        sub-class' method does not implement `keepdims` any
        exceptions will be raised.
    initial : scalar, optional
        Starting value for the sum. See `~numpy.ufunc.reduce` for details.
    
        .. versionadded:: 1.15.0
    
    where : array_like of bool, optional
        Elements to include in the sum. See `~numpy.ufunc.reduce` for details.
    
        .. versionadded:: 1.17.0
    
    Returns
    -------
    sum_along_axis : ndarray
        An array with the same shape as `a`, with the specified
        axis removed.   If `a` is a 0-d array, or if `axis` is None, a scalar
        is returned.  If an output array is specified, a reference to
        `out` is returned.
    
    See Also
    --------
    ndarray.sum : Equivalent method.
    
    add.reduce : Equivalent functionality of `add`.
    
    cumsum : Cumulative sum of array elements.
    
    trapz : Integration of array values using the composite trapezoidal rule.
    
    mean, average
    
    Notes
    -----
    Arithmetic is modular when using integer types, and no error is
    raised on overflow.
    
    The sum of an empty array is the neutral element 0:
    
    >>> np.sum([])
    0.0
    
    For floating point numbers the numerical precision of sum (and
    ``np.add.reduce``) is in general limited by directly adding each number
    individually to the result causing rounding errors in every step.
    However, often numpy will use a  numerically better approach (partial
    pairwise summation) leading to improved precision in many use-cases.
    This improved precision is always provided when no ``axis`` is given.
    When ``axis`` is given, it will depend on which axis is summed.
    Technically, to provide the best speed possible, the improved precision
    is only used when the summation is along the fast axis in memory.
    Note that the exact precision may vary depending on other parameters.
    In contrast to NumPy, Python's ``math.fsum`` function uses a slower but
    more precise approach to summation.
    Especially when summing a large number of lower precision floating point
    numbers, such as ``float32``, numerical errors can become significant.
    In such cases it can be advisable to use `dtype="float64"` to use a higher
    precision for the output.
    
    Examples
    --------
    >>> np.sum([0.5, 1.5])
    2.0
    >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
    1
    >>> np.sum([[0, 1], [0, 5]])
    6
    >>> np.sum([[0, 1], [0, 5]], axis=0)
    array([0, 6])
    >>> np.sum([[0, 1], [0, 5]], axis=1)
    array([1, 5])
    >>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1)
    array([1., 5.])
    
    If the accumulator is too small, overflow occurs:
    
    >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
    -128
    
    You can also start the sum with a value other than zero:
    
    >>> np.sum([10], initial=5)
    15

不同于inspect只能查询由python编写的代码,help也可以查询其他代码编译后的函数参数,如C编译后的代码也能成功查询。

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-04-22 18:32:27  更:2022-04-22 18:34:14 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/15 18:06:48-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码