知行编程网知行编程网  2022-10-03 23:00 知行编程网 隐藏边栏  144 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于一分钟学会如何查看Python内置函数的用法及其源码的相关知识,包括python中eval函数作用,以及max函数用法这些编程知识,希望对大家有参考作用。

一分钟了解如何查看Python内置函数的用法和源码

当我们使用 Python 进行各种分析时,会用到各种函数。比如我们在使用SQL的时候,经常会用到join、max等各种函数。如果我们想看看Python有没有这个功能,这个时候可能是可以的。大多数人都知道百度,那么如何使用Python本身来查找函数并学习如何使用它们而不是百度呢?下面,小白总结了一些自己的经历~

比如我们在使用math模块,但是不知道这个模块下有没有我们自己常用的函数,那怎么办呢?

方法一

import math
dir(math)

首先我们导入这个模块,使用dir函数查看这个模块下有哪些函数。

['__doc__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'acos',
 'acosh',
 'asin',
 'asinh',
 'atan',
 'atan2',
 'atanh',
 'ceil',
 'copysign',
 'cos',
 'cosh',
 'degrees',
 'e',
 'erf',
 'erfc',
 'exp',
 'expm1',
 'fabs',
 'factorial',
 'floor',
 'fmod',
 'frexp',
 'fsum',
 'gamma',
 'gcd',
 'hypot',
 'inf',
 'isclose',
 'isfinite',
 'isinf',
 'isnan',
 'ldexp',
 'lgamma',
 'log',
 'log10',
 'log1p',
 'log2',
 'modf',
 'nan',
 'pi',
 'pow',
 'radians',
 'sin',
 'sinh',
 'sqrt',
 'tan',
 'tanh',
 'tau',
 'trunc']

这个方法是获取函数列表,当然这里也可以使用帮助函数:

import math
help(math)

一分钟了解如何查看Python内置函数的用法和源码

如果对函数还不是很了解,可以到方法文件中查看函数的定义,使用***.__file__查看位置,然后打开后缀为.py的文件。

import random
random.__file__

结果为:这样就可以到这个py文件中查看源码

'D:\\Anaconda2\\envs\\py3\\lib\\random.py'

这里需要注意一下:

***.pyc文件是编译后的文件,打开看不懂,所以看***.py文件。

在里面,你可以搜索你想看的功能,以及具体的定义。例如,你搜索 expovariate 函数,并粘贴下面的方法,以便你可以看到该方法是如何声明的。方便且易于理解吗?更清楚了~

def expovariate(self, lambd):
        """Exponential distribution.
        lambd is 1.0 divided by the desired mean.  It should be
        nonzero.  (The parameter would be called "lambda", but that is
        a reserved word in Python.)  Returned values range from 0 to
        positive infinity if lambd is positive, and from negative
        infinity to 0 if lambd is negative.
        """
        # lambd: rate lambd = 1/mean
        # ('lambda' is a Python reserved word)
 
        # we use 1-random() instead of random() to preclude the
        # possibility of taking the log of zero.
        return -_log(1.0 - self.random())/lambd

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享