2012-07-15 67 views
1

如果我想要查看一個方法的作用,例如隨機模塊中的gauss方法,我將如何使用Python解釋器進行操作?例如,我輸入隨機導入Python解釋器的控制檯後,我可以做什麼來隨機地在模塊中找到方法gauss的實際代碼,而無需查看實際文件。提前致謝!閱讀庫方法定義

回答

5

嘗試:

import inspect 
inspect.getsource(random.gauss) 
+0

的建議爲何不乾脆:'inspect.getsource(random.gauss)' – jamylak 2012-07-15 05:29:55

+0

@jamylak:哦,是的!謝謝 :) – SuperSaiyan 2012-07-15 05:31:42

2

雖然不能從默認的Python殼,這是衆多功能之一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