Learn Python More
0, 看了一个python项目开源源码, 才知道现在这点python知识实在是弱爆了..
尼玛就像学了2500个常用汉字, 然后要去理解"楚辞"..
代码如下, 解释一点一点从网上查, 随后:
###############################################################################
class BaseEstimator(object):
"""Base class for all estimators in scikit-learn Notes
-----
All estimators should specify all the parameters that can be set
at the class level in their __init__ as explicit keyword
arguments (no *args, **kwargs).
""" @classmethod
def _get_param_names(cls):
"""Get parameter names for the estimator"""
try:
# fetch the constructor or the original constructor before
# deprecation wrapping if any
init = getattr(cls.__init__, 'deprecated_original', cls.__init__) # introspect the constructor arguments to find the model parameters
# to represent
args, varargs, kw, default = inspect.getargspec(init)
if not varargs is None:
raise RuntimeError("scikit-learn estimators should always "
"specify their parameters in the signature"
" of their __init__ (no varargs)."
" %s doesn't follow this convention."
% (cls, ))
# Remove 'self'
# XXX: This is going to fail if the init is a staticmethod, but
# who would do this?
args.pop(0)
except TypeError:
# No explicit __init__
args = []
args.sort()
return args def get_params(self, deep=True):
"""Get parameters for this estimator. Parameters
----------
deep: boolean, optional
If True, will return the parameters for this estimator and
contained subobjects that are estimators. Returns
-------
params : mapping of string to any
Parameter names mapped to their values.
"""
out = dict()
for key in self._get_param_names():
# We need deprecation warnings to always be on in order to
# catch deprecated param values.
# This is set in utils/__init__.py but it gets overwritten
# when running under python3 somehow.
warnings.simplefilter("always", DeprecationWarning)
try:
with warnings.catch_warnings(record=True) as w:
value = getattr(self, key, None)
if len(w) and w[0].category == DeprecationWarning:
# if the parameter is deprecated, don't show it
continue
finally:
warnings.filters.pop(0) # XXX: should we rather test if instance of estimator?
if deep and hasattr(value, 'get_params'):
deep_items = value.get_params().items()
out.update((key + '__' + k, val) for k, val in deep_items)
out[key] = value
return out def set_params(self, **params):
"""Set the parameters of this estimator. The method works on simple estimators as well as on nested objects
(such as pipelines). The former have parameters of the form
``<component>__<parameter>`` so that it's possible to update each
component of a nested object. Returns
-------
self
"""
if not params:
# Simple optimisation to gain speed (inspect is slow)
return self
valid_params = self.get_params(deep=True)
for key, value in six.iteritems(params):
split = key.split('__', 1)
if len(split) > 1:
# nested objects case
name, sub_name = split
if not name in valid_params:
raise ValueError('Invalid parameter %s for estimator %s' %
(name, self))
sub_object = valid_params[name]
sub_object.set_params(**{sub_name: value})
else:
# simple objects case
if not key in valid_params:
raise ValueError('Invalid parameter %s ' 'for estimator %s'
% (key, self.__class__.__name__))
setattr(self, key, value)
return self def __repr__(self):
class_name = self.__class__.__name__
return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False),
offset=len(class_name),),) def __str__(self):
class_name = self.__class__.__name__
return '%s(%s)' % (class_name,
_pprint(self.get_params(deep=True),
offset=len(class_name), printer=str,),)
1, @classmethod
http://www.cnblogs.com/chenzehe/archive/2010/09/01/1814639.html
classmethod:类方法
staticmethod:静态方法
在python中,静态方法和类方法都是可以通过类对象和类对象实例访问。但是区别是:
- @classmethod 是一个函数修饰符,它表示接下来的是一个类方法,而对于平常我们见到的则叫做实例方法。 类方法的第一个参数cls,而实例方法的第一个参数是self,表示该类的一个实例。
- 普通对象方法至少需要一个self参数,代表类对象实例
- 类方法有类变量cls传入,从而可以用cls做一些相关的处理。并且有子类继承时,调用该类方法时,传入的类变量cls是子类,而非父类。 对于类方法,可以通过类来调用,就像C.f(),有点类似C++中的静态方法, 也可以通过类的一个实例来调用,就像C().f(),这里C(),写成这样之后它就是类的一个实例了。
- 静态方法则没有,它基本上跟一个全局函数相同,一般来说用的很少
2, getarrt() 函数
详解: http://www.cnblogs.com/pylemon/archive/2011/06/09/2076862.html
简单的说:
这个函数的作用相当于是 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')
Learn Python More的更多相关文章
- 笨办法学 Python (Learn Python The Hard Way)
最近在看:笨办法学 Python (Learn Python The Hard Way) Contents: 译者前言 前言:笨办法更简单 习题 0: 准备工作 习题 1: 第一个程序 习题 2: 注 ...
- 《Learn python the hard way》Exercise 48: Advanced User Input
这几天有点时间,想学点Python基础,今天看到了<learn python the hard way>的 Ex48,这篇文章主要记录一些工具的安装,以及scan 函数的实现. 首先与Ex ...
- [IT学习]Learn Python the Hard Way (Using Python 3)笨办法学Python3版本
黑客余弦先生在知道创宇的知道创宇研发技能表v3.1中提到了入门Python的一本好书<Learn Python the Hard Way(英文版链接)>.其中的代码全部是2.7版本. 如果 ...
- 学 Python (Learn Python The Hard Way)
学 Python (Learn Python The Hard Way) Contents: 译者前言 前言:笨办法更简单 习题 0: 准备工作 习题 1: 第一个程序 习题 2: 注释和井号 习题 ...
- 快速入门:十分钟学会PythonTutorial - Learn Python in 10 minutes
This tutorial is available as a short ebook. The e-book features extra content from follow-up posts ...
- Python basic (from learn python the hard the way)
1. How to run the python file? python ...py 2. UTF-8 is a character encoding, just like ASCII. 3. ro ...
- Learn Python the hard way, ex41 来自Percal 25 号星星的哥顿人
我承认,我偷懒了,少打了大量代码(剧情),英文太差,下次可以编个中文的试试 #!/urs/bin/python #coding:utf-8 from sys import exit from rand ...
- 笨办法学Python(learn python the hard way)--练习程序31-35
下面是练习31-练习35,基于python3 #ex31.py 1 print("You enter a dark room witn two doors. Do you go throug ...
- Learn Python the hard way, ex35 分支和函数
#!/usr/bin/python #coding:utf-8 from sys import exit def gold_room(): print "this room is full ...
- learn python, ref, diveintopython 分类: python 2015-07-22 14:42 14人阅读 评论(0) 收藏
for notes of learing python. // just ignore the ugly/wrong highlight for python code. ""&q ...
随机推荐
- “ddl”有一个无效 SelectedValue,因为它不在项目列表中。
“ddl_ekt”有一个无效 SelectedValue,因为它不在项目列表中. 怎么回事 现象: 在用户控件的page_load事件里绑定下拉框,报上面错误 解决: 将下拉框绑定,放在page_In ...
- oracle存储过程的例子
oracle存储过程的例子 分类: 数据(仓)库及处理 2010-05-03 17:15 1055人阅读 评论(2)收藏 举报 认识存储过程和函数 存储过程和函数也是一种PL/SQL块,是存入数据库的 ...
- 实验数据结构——KMP算法Test.ming
翻译计划 小明初学者C++,它确定了四个算术.关系运算符.逻辑运算.颂值操作.输入输出.使用简单的选择和循环结构.但他的英语不是很好,记住太多的保留字,他利用汉语拼音的保留字,小屋C++,发明 ...
- 乐在其中设计模式(C#) - 抽象工厂模式(Abstract Factory Pattern)
原文:乐在其中设计模式(C#) - 抽象工厂模式(Abstract Factory Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 抽象工厂模式(Abstract Factor ...
- 交换A与B值的四种方法
在网上看到了这样一道面试题,"int A=5,int B=2,怎样交换A与B的值",或许这是一道简单到不能再简单的题,但能作为一道面试题,肯定有其独特之处 大多数人会通过定义第三个 ...
- 最短路径:Dijkstra,Bellman,SPFA,Floyd该算法的实施
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzQ4NzA1MQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQk ...
- Oracle 初始化参数文件pfile和spfile
pfile和spfile差额 pfile :Oracle 9i之前.ORACLE使用我们一直PFILE存储的初始化参数,,能够在操作系统级别改动. 当spfile文件改动出现错误导致oracle无法启 ...
- poj2112 Optimal Milking --- 最大流量,二分法
nx一个挤奶器,ny奶牛,每个挤奶罐为最m奶牛使用. 现在给nx+ny在矩阵之间的距离.要求使所有奶牛挤奶到挤奶正在旅程,最小的个体奶牛步行距离的最大值. 始感觉这个类似二分图匹配,不同之处在于挤奶器 ...
- 获取Winform窗体、工作区 宽度、高度、命名空间、菜单栏高度等收集
MessageBox.Show("当前窗体标题栏高"+(this.Height - this.ClientRectangle.Height).ToString());//当前窗体标 ...
- Cygwin编译自己定义OpenCV库报错:opencv_contrib: LOCAL_SRC_FILES points to a missing file
今天受命帮师弟调个OpenCV4Android 识别银行卡的程序,版本号为OpenCV4Android2.4.9,使用方式为前文介绍的第一种方式,即通过jni调用opencv.如杂家前文所述,配套的N ...