0, 看了一個python項目開源源碼, 才知道如今這點python知識實在是弱爆了.. html
尼瑪就像學了2500個經常使用漢字, 而後要去理解"楚辭"..python
代碼以下, 解釋一點一點從網上查, 隨後:app
1 ############################################################################### 2 class BaseEstimator(object): 3 """Base class for all estimators in scikit-learn 4 5 Notes 6 ----- 7 All estimators should specify all the parameters that can be set 8 at the class level in their __init__ as explicit keyword 9 arguments (no *args, **kwargs). 10 """ 11 12 @classmethod 13 def _get_param_names(cls): 14 """Get parameter names for the estimator""" 15 try: 16 # fetch the constructor or the original constructor before 17 # deprecation wrapping if any 18 init = getattr(cls.__init__, 'deprecated_original', cls.__init__) 19 20 # introspect the constructor arguments to find the model parameters 21 # to represent 22 args, varargs, kw, default = inspect.getargspec(init) 23 if not varargs is None: 24 raise RuntimeError("scikit-learn estimators should always " 25 "specify their parameters in the signature" 26 " of their __init__ (no varargs)." 27 " %s doesn't follow this convention." 28 % (cls, )) 29 # Remove 'self' 30 # XXX: This is going to fail if the init is a staticmethod, but 31 # who would do this? 32 args.pop(0) 33 except TypeError: 34 # No explicit __init__ 35 args = [] 36 args.sort() 37 return args 38 39 def get_params(self, deep=True): 40 """Get parameters for this estimator. 41 42 Parameters 43 ---------- 44 deep: boolean, optional 45 If True, will return the parameters for this estimator and 46 contained subobjects that are estimators. 47 48 Returns 49 ------- 50 params : mapping of string to any 51 Parameter names mapped to their values. 52 """ 53 out = dict() 54 for key in self._get_param_names(): 55 # We need deprecation warnings to always be on in order to 56 # catch deprecated param values. 57 # This is set in utils/__init__.py but it gets overwritten 58 # when running under python3 somehow. 59 warnings.simplefilter("always", DeprecationWarning) 60 try: 61 with warnings.catch_warnings(record=True) as w: 62 value = getattr(self, key, None) 63 if len(w) and w[0].category == DeprecationWarning: 64 # if the parameter is deprecated, don't show it 65 continue 66 finally: 67 warnings.filters.pop(0) 68 69 # XXX: should we rather test if instance of estimator? 70 if deep and hasattr(value, 'get_params'): 71 deep_items = value.get_params().items() 72 out.update((key + '__' + k, val) for k, val in deep_items) 73 out[key] = value 74 return out 75 76 def set_params(self, **params): 77 """Set the parameters of this estimator. 78 79 The method works on simple estimators as well as on nested objects 80 (such as pipelines). The former have parameters of the form 81 ``<component>__<parameter>`` so that it's possible to update each 82 component of a nested object. 83 84 Returns 85 ------- 86 self 87 """ 88 if not params: 89 # Simple optimisation to gain speed (inspect is slow) 90 return self 91 valid_params = self.get_params(deep=True) 92 for key, value in six.iteritems(params): 93 split = key.split('__', 1) 94 if len(split) > 1: 95 # nested objects case 96 name, sub_name = split 97 if not name in valid_params: 98 raise ValueError('Invalid parameter %s for estimator %s' % 99 (name, self)) 100 sub_object = valid_params[name] 101 sub_object.set_params(**{sub_name: value}) 102 else: 103 # simple objects case 104 if not key in valid_params: 105 raise ValueError('Invalid parameter %s ' 'for estimator %s' 106 % (key, self.__class__.__name__)) 107 setattr(self, key, value) 108 return self 109 110 def __repr__(self): 111 class_name = self.__class__.__name__ 112 return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False), 113 offset=len(class_name),),) 114 115 def __str__(self): 116 class_name = self.__class__.__name__ 117 return '%s(%s)' % (class_name, 118 _pprint(self.get_params(deep=True), 119 offset=len(class_name), printer=str,),)
1, @classmethod框架
http://www.cnblogs.com/chenzehe/archive/2010/09/01/1814639.html 函數
classmethod:類方法
staticmethod:靜態方法fetch
在python中,靜態方法和類方法都是能夠經過類對象和類對象實例訪問。可是區別是:this
2, getarrt() 函數spa
詳解: http://www.cnblogs.com/pylemon/archive/2011/06/09/2076862.html.net
簡單的說:code
這個函數的做用至關因而 object.name. 只不過這裏能夠把name做爲一個變量去處理.
這就有很大的方便. 之前要傳回調函數, 須要傳個(函數) 對象, 如今穿個string 就能夠了.
string麼, 隨意多了.. 不用先定義好.
例:一個模塊支持html、text、xml等格式的打印,根據傳入的formate參數的不一樣,調用不一樣的函數實現幾種格式的輸出
import
statsout
def
output(data,
format
=
"text"
):
output_function
=
getattr
(statsout,
"output_%s"
%
format
)
return
output_function(data)
詳解: http://my.oschina.net/taisha/blog/55597
簡單來講: inspect 模塊是能夠提供python 反射機制:
(1).對是不是模塊,框架,函數等進行類型檢查。
(2).獲取源碼
(3).獲取類或函數的參數的信息
(4).解析堆棧
getargspec(func):
僅用於方法,獲取方法聲明的參數,返回元組,分別是(普通參數名的列表, *參數名, **參數名, 默認值元組)。若是沒有值,將是空列表和3個None。若是是2.6以上版本,將返回一個命名元組(Named Tuple),即除了索引外還可使用屬性名訪問元組中的元素。
好了_get_param_names 這個函數意思是: 拿到這個類的構造函數的參數.
4, 關於函數參數:
http://blog.csdn.net/qinyilang/article/details/5484415
在python裏, 定義一個函數, 能夠有如下4類參數:
1)必須的參數
2)可選的參數
3)過量的位置參數
4)過量的關鍵字參數
1),2), 常常用, 3), 4) 是啥啊, 常常看人這麼寫 def func(*args, *kwargs)
這裏 *args 就是3), 至關於C 裏的變長參數列表..
**kwargs 是4), 叫" 關鍵詞參數".. 好比: def accept(**kwargs):
kwargs 是一個字典, 裏面有想用到的任何變量名. ..
能夠這麼調用: accept(foo='bar', spam='eggs')