如果我想查看一个方法的作用,例如模块 random 中的方法 gauss,我将如何使用 Python 解释器来做呢?例如,在我在 Python 解释器的控制台中键入 import random 之后,我可以做些什么来找出模块 random 中方法 gauss 的实际代码,而无需查看实际文件。提前致谢!
问问题
99 次
3 回答
5
尝试:
import inspect
inspect.getsource(random.gauss)
于 2012-07-15T05:23:45.297 回答
3
如果您使用的是IPython,您可以这样做:
>>> random.gauss??
于 2012-07-15T05:22:43.300 回答
2
虽然它在默认的 python shell 中不可用,但这是ipython
.
In [4]: %psource random.gauss
def gauss(self, mu, sigma):
"""Gaussian distribution.
mu is the mean, and sigma is the standard deviation. This is
slightly faster than the normalvariate() function.
Not thread-safe without a lock around calls.
"""
# When x and y are two variables from [0, 1), uniformly
# distributed, then
#
# cos(2*pi*x)*sqrt(-2*log(1-y))
# sin(2*pi*x)*sqrt(-2*log(1-y))
#
# are two *independent* variables with normal distribution
# (mu = 0, sigma = 1).
# (Lambert Meertens)
# (corrected version; bug discovered by Mike Miller, fixed by LM)
# Multithreading note: When two threads call this function
# simultaneously, it is possible that they will receive the
# same return value. The window is very small though. To
# avoid this, you have to use a lock around all calls. (I
# didn't want to slow this down in the serial case by using a
# lock here.)
random = self.random
z = self.gauss_next
self.gauss_next = None
if z is None:
x2pi = random() * TWOPI
g2rad = _sqrt(-2.0 * _log(1.0 - random()))
z = _cos(x2pi) * g2rad
self.gauss_next = _sin(x2pi) * g2rad
return mu + z*sigma
这与random.gauss??
@icktoofay 建议的打字相同
于 2012-07-15T05:24:16.880 回答