
正文
包含隐式函数python的词条
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
Python 有什么奇技淫巧
Python奇技淫巧
当发布python第三方package时, 并不希望代码中所有隐式函数python的函数或者class可以被外部import, 在 __init__.py 中添加 __all__ 属性,
该list中填写可以import隐式函数python的类或者函数名, 可以起到限制的import的作用, 防止外部import其他函数或者类
#!/usr/bin/env python
# -*- coding: utf-8 -*-
frombaseimportAPIBase
fromclientimportClient
fromdecoratorimportinterface, export, stream
fromserverimportServer
fromstorageimportStorage
fromutilimport(LogFormatter, disable_logging_to_stderr,
enable_logging_to_kids, info)
__all__ = ['APIBase','Client','LogFormatter','Server',
'Storage','disable_logging_to_stderr','enable_logging_to_kids',
'export','info','interface','stream']
with的魔力
with语句需要支持 上下文管理协议的对象 , 上下文管理协议包含 __enter__ 和 __exit__ 两个方法. with语句建立运行时上下文需要通过这两个方法执行 进入和退出 操作.
其中 上下文表达式 是跟在with之后的表达式, 该表示大返回一个上下文管理对象
# 常见with使用场景
withopen("test.txt","r")asmy_file:# 注意, 是__enter__()方法的返回值赋值给了my_file,
forlineinmy_file:
print line
详细原理可以查看这篇文章, 浅谈 Python 的 with 语句
知道具体原理, 隐式函数python我们可以自定义支持上下文管理协议的类, 类中实现 __enter__ 和 __exit__ 方法
#!/usr/bin/env python
# -*- coding: utf-8 -*-
classMyWith(object):
def__init__(self):
print"__init__ method"
def__enter__(self):
print"__enter__ method"
returnself# 返回对象给as后的变量
def__exit__(self, exc_type, exc_value, exc_traceback):
print"__exit__ method"
ifexc_tracebackisNone:
print"Exited without Exception"
returnTrue
else:
print"Exited with Exception"
returnFalse
deftest_with():
withMyWith()asmy_with:
print"running my_with"
print"------分割线-----"
withMyWith()asmy_with:
print"running before Exception"
raiseException
print"running after Exception"
if__name__ =='__main__':
test_with()
执行结果如下:
__init__ method
__enter__ method
running my_with
__exit__ method
ExitedwithoutException
------分割线-----
__init__ method
__enter__ method
running before Exception
__exit__ method
ExitedwithException
Traceback(most recent call last):
File"bin/python", line34,inmodule
exec(compile(__file__f.read(), __file__, "exec"))
File"test_with.py", line33,inmodule
test_with()
File"test_with.py", line28,intest_with
raiseException
Exception
证明了会先执行 __enter__ 方法, 然后调用with内的逻辑, 最后执行 __exit__ 做退出处理, 并且, 即使出现异常也能正常退出
filter的用法
相对 filter 而言, map和reduce使用的会更频繁一些, filter 正如其名字, 按照某种规则 过滤 掉一些元素
#!/usr/bin/env python
# -*- coding: utf-8 -*-
lst = [1,2,3,4,5,6]
# 所有奇数都会返回True, 偶数会返回False被过滤掉
print filter(lambda x: x % 2!=0, lst)
#输出结果
[1,3,5]
一行作判断
当条件满足时, 返回的为等号后面的变量, 否则返回else后语句
lst = [1,2,3]
new_lst = lst[0]iflstisnotNoneelseNone
printnew_lst
# 打印结果
1
装饰器之单例
使用装饰器实现简单的单例模式
# 单例装饰器
defsingleton(cls):
instances = dict() # 初始为空
def_singleton(*args, **kwargs):
ifclsnotininstances:#如果不存在, 则创建并放入字典
instances[cls] = cls(*args, **kwargs)
returninstances[cls]
return_singleton
@singleton
classTest(object):
pass
if__name__ =='__main__':
t1 = Test()
t2 = Test()
# 两者具有相同的地址
printt1, t2
staticmethod装饰器
类中两种常用的装饰, 首先区分一下他们
普通成员函数, 其中第一个隐式参数为 对象
classmethod装饰器 , 类方法(给人感觉非常类似于OC中的类方法), 其中第一个隐式参数为 类
staticmethod装饰器 , 没有任何隐式参数. python中的静态方法类似与C++中的静态方法
#!/usr/bin/env python
# -*- coding: utf-8 -*-
classA(object):
# 普通成员函数
deffoo(self, x):
print "executing foo(%s, %s)"% (self, x)
@classmethod# 使用classmethod进行装饰
defclass_foo(cls, x):
print "executing class_foo(%s, %s)"% (cls, x)
@staticmethod# 使用staticmethod进行装饰
defstatic_foo(x):
print "executing static_foo(%s)"% x
deftest_three_method():
obj = A()
# 直接调用噗通的成员方法
obj.foo("para")# 此处obj对象作为成员函数的隐式参数, 就是self
obj.class_foo("para")# 此处类作为隐式参数被传入, 就是cls
A.class_foo("para")#更直接的类方法调用
obj.static_foo("para")# 静态方法并没有任何隐式参数, 但是要通过对象或者类进行调用
A.static_foo("para")
if__name__=='__main__':
test_three_method()
# 函数输出
executing foo(__main__.Aobject at0x100ba4e10, para)
executing class_foo(class'__main__.A',para)
executing class_foo(class'__main__.A',para)
executing static_foo(para)
executing static_foo(para)
property装饰器
定义私有类属性
将 property 与装饰器结合实现属性私有化( 更简单安全的实现get和set方法 )
#python内建函数
property(fget=None, fset=None, fdel=None, doc=None)
fget 是获取属性的值的函数, fset 是设置属性值的函数, fdel 是删除属性的函数, doc 是一个字符串(like a comment).从实现来看隐式函数python,这些参数都是可选的
property有三个方法 getter() , setter() 和 delete() 来指定fget, fset和fdel。 这表示以下这行
classStudent(object):
@property #相当于property.getter(score) 或者property(score)
defscore(self):
returnself._score
@score.setter #相当于score = property.setter(score)
defscore(self, value):
ifnotisinstance(value, int):
raiseValueError('score must be an integer!')
ifvalue 0orvalue 100:
raiseValueError('score must between 0 ~ 100!')
self._score = value
iter魔法
通过yield和 __iter__ 的结合, 我们可以把一个对象变成可迭代的
通过 __str__ 的重写, 可以直接通过想要的形式打印对象
#!/usr/bin/env python
# -*- coding: utf-8 -*-
classTestIter(object):
def__init__(self):
self.lst = [1,2,3,4,5]
defread(self):
foreleinxrange(len(self.lst)):
yieldele
def__iter__(self):
returnself.read()
def__str__(self):
return','.join(map(str, self.lst))
__repr__ = __str__
deftest_iter():
obj = TestIter()
fornuminobj:
printnum
printobj
if__name__ =='__main__':
test_iter()
神奇partial
partial使用上很像C++中仿函数(函数对象).
在stackoverflow给出了类似与partial的运行方式
defpartial(func, *part_args):
defwrapper(*extra_args):
args = list(part_args)
args.extend(extra_args)
returnfunc(*args)
returnwrapper
利用用闭包的特性绑定预先绑定一些函数参数, 返回一个可调用的变量, 直到真正的调用执行
#!/usr/bin/env python
# -*- coding: utf-8 -*-
fromfunctoolsimportpartial
defsum(a, b):
returna + b
deftest_partial():
fun = partial(sum, 2)# 事先绑定一个参数, fun成为一个只需要一个参数的可调用变量
printfun(3)# 实现执行的即是sum(2, 3)
if__name__ =='__main__':
test_partial()
# 执行结果
5
神秘eval
eval我理解为一种内嵌的python解释器(这种解释可能会有偏差), 会解释字符串为对应的代码并执行, 并且将执行结果返回
看一下下面这个例子
#!/usr/bin/env python
# -*- coding: utf-8 -*-
deftest_first():
return3
deftest_second(num):
returnnum
action = { # 可以看做是一个sandbox
"para":5,
"test_first": test_first,
"test_second": test_second
}
deftest_eavl():
condition = "para == 5 and test_second(test_first) 5"
res = eval(condition, action) # 解释condition并根据action对应的动作执行
printres
if__name__ =='_
exec
exec在Python中会忽略返回值, 总是返回None, eval会返回执行代码或语句的返回值
exec 和 eval 在执行代码时, 除了返回值其他行为都相同
在传入字符串时, 会使用 compile(source, 'string', mode) 编译字节码. mode的取值为 exec 和 eval
#!/usr/bin/env python
# -*- coding: utf-8 -*-
deftest_first():
print"hello"
deftest_second():
test_first()
print"second"
deftest_third():
print"third"
action = {
"test_second": test_second,
"test_third": test_third
}
deftest_exec():
exec"test_second"inaction
if__name__ =='__main__':
test_exec() # 无法看到执行结果
getattr
getattr(object, name[, default]) Return the value of
the named attribute of object. name must be a string. If the string is
the name of one of the object’s attributes, the result is the value of
that attribute. For example, getattr(x, ‘foobar’) is equivalent to
x.foobar. If the named attribute does not exist, default is returned if
provided, otherwise AttributeError is raised.
通过string类型的name, 返回对象的name属性(方法)对应的值, 如果属性不存在, 则返回默认值, 相当于object.name
# 使用范例
classTestGetAttr(object):
test = "test attribute"
defsay(self):
print"test method"
deftest_getattr():
my_test = TestGetAttr()
try:
printgetattr(my_test,"test")
exceptAttributeError:
print"Attribute Error!"
try:
getattr(my_test, "say")()
exceptAttributeError:# 没有该属性, 且没有指定返回值的情况下
print"Method Error!"
if__name__ =='__main__':
test_getattr()
# 输出结果
test attribute
test method
命令行处理
defprocess_command_line(argv):
"""
Return a 2-tuple: (settings object, args list).
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
ifargvisNone:
argv = sys.argv[1:]
# initialize the parser object:
parser = optparse.OptionParser(
formatter=optparse.TitledHelpFormatter(width=78),
add_help_option=None)
# define options here:
parser.add_option( # customized description; put --help last
'-h','--help', action='help',
help='Show this help message and exit.')
settings, args = parser.parse_args(argv)
# check number of arguments, verify values, etc.:
ifargs:
parser.error('program takes no command-line arguments; '
'"%s" ignored.'% (args,))
# further process settings args if necessary
returnsettings, args
defmain(argv=None):
settings, args = process_command_line(argv)
# application code here, like:
# run(settings, args)
return0# success
if__name__ =='__main__':
status = main()
sys.exit(status)
读写csv文件
# 从csv中读取文件, 基本和传统文件读取类似
importcsv
withopen('data.csv','rb')asf:
reader = csv.reader(f)
forrowinreader:
printrow
# 向csv文件写入
importcsv
withopen('data.csv','wb')asf:
writer = csv.writer(f)
writer.writerow(['name','address','age'])# 单行写入
data = [
( 'xiaoming ','china','10'),
( 'Lily','USA','12')]
writer.writerows(data) # 多行写入
各种时间形式转换
只发一张网上的图, 然后差文档就好了, 这个是记不住的
字符串格式化
一个非常好用, 很多人又不知道的功能
name ="andrew"
"my name is {name}".format(name=name)
'my name is andrew'
相关问答
Q1: Python 中max( )函数与lambda隐式函数结合使用时出错。
print max.__doc__max(iterable[, key=func]) - valuemax(a, b, c, ...[, key=func]) - valueWith a single iterable argument, return its largest item.With two or more arguments, return the largest argument. 后面的func,是比较函数,条件成立后,max执行结束。 所以: array1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] max(array1, key=lambda x: x 6) 7 如果: max([i for i in range(0,9)], key=lambda x: x = 6)6 执行结果就是6
Q2: python函数的返回值?
题主你好,
关键点在于函数如果没有明确使用return关键字指定函数的返回值,则默认返回值是none.
-----
所以temp = hello()这句的理解就是: 执行hello()这个函数, 并且把函数的返回值赋给变量temp, 但hello()函数中没有return语句, 所以hello()函数的返回值为默认的none.
-----
题主还可以在hello()函数最后加一个: return 123
然后再行一下看看,就明白了.
=====
希望可以帮到题主, 欢迎追问.
Q3: Python 数据模型
Python 风格的关键完全体现在 Python 的数据模型上,数据模型所描述的 API ,为使用最地道的语言特性来构建开发者自己的对象提供了工具。
当 Python 解析器遇到特殊句法时,会使用特殊方法去激活一些基本的对象操作。特殊方法以双下划线开头,以双下划线结尾。如: obj[key] 的背后就是 __getitem__ 方法。魔术方法是特殊方法的昵称,特殊方法也叫双下方法。
使用 __getitem__ 和 __len__ 创建一摞有序的纸牌:
上面的例子,使用 collections.namedtuple 构建了一个简单的类来表示一张纸牌, namedtuple 用以构建只有少数属性但没有方法的类。
我们自定义的 FrenchDeck 类可以像任何 python 标准集合类型一样使用 len() 函数,查看一叠牌有多少张:
也可以像列表一样,使用位置索引, d[i] 将调用 __getitem__ 方法:
也可以使用标准库模块提供的 random.choice 方法,从序列中随机选取一个元素。下面,我们如随机取出一张纸牌:
现在我们已经体会到通过 python 特殊方法,来使用 Python 数据模型的 2 个好处:
因为 __getitem__ 方法把 [] 操作交给了 self.cards 列表,所以我们的 FrenchDeck 实例自动支持切片:
仅仅实现了 __getitem__ 方法,这一摞牌即变得可迭代:
运行结果:
也可以直接调用内置的 reversed 函数,反向迭代 FrenchDeck 实例:
运行结果:
迭代通常是隐式的,比如一个集合类型没有实现 __contains__ 方法,那么 in 运算符就会按顺序做一次迭代搜索。
因此, in 运算符可以用在我们的 FrenchDeck 实例上,因为它是可迭代的:
FrenchDeck 还可以使用 Python 标准库中的 sorted 函数,实现排序:
首先定义一个排序依据的函数:
优先按 rank 的大小排序,rank 相同时则比较 suit 的值:
运行结果:
优先按 suit 的大小排序,suit 相同时则比较 rank 的值:
运行结果:
按照目前的设计,FrenchDeck 还不支持洗牌,因为它是不可变的:
shuffle 函数要调换集合中元素的位置,而 FrenchDeck 只实现了不可变的序列协议,可变的序列还必须提供 __setitem__ 方法:
洗牌:
没有任何的返回值,可见 random.shuffle 就地修改了可变序列 d 。为便于观察结果,我们定义输入的输出函数:
运行结果:
每次洗牌,都是一个随机的序列:
首先明确一点,特殊方法的存在是为了被 Python 解析器调用的,例如:我们不会使用 obj.__len__() 这种写法,而是 len(obj) 。在执行 len(obj) 时,如果 obj 是一个自定义类的对象,那么 Python 会自己去调用我们实现的 __len__ 方法。
对于 Python 内置的数据类型,比如列表、字符串、字节序列等,那么 CPython 会抄个近路, __len__ 实际上会返回 PyVarObject 里的 ob_size 属性,这是因为直接读取属性比调用一个方法要快得多。
很多时候,特殊方法的调用是隐式的,比如 for i in x: 这个语句其实是调用 iter(x) ,而这个函数的背后是 x.__iter__() 方法。
通过内置函数如来使用特殊方法是最好的选择。这些内置函数不仅会调用这些方法,通常还提供额外的好处,对于内置类型来说,它们的速度更快。
下面,我们通过定义一个简单的二维向量类,再来体会一下 Python 特殊方法的美妙:
使用 Vector 类,就像使用 Python 内置的数据类型一样简单:
Q4: 隐式马尔科夫模型 及 Python + HMMlearn的使用
hmmlearn
隐式马尔科夫模型Hidden Markov Models(HMMs) 是一种通用的概率模型。一个可观测的变量X的序列被一个内部的隐藏状态Z所生成。其中,隐藏状态Z无法被直接观测。在隐藏状态之间的转移被假设是通过 马尔科夫链(Markov chain) 的形式。
模型可以表示为 起始概率向量 和转移概率矩阵 . 一个观测量生成的概率可以是关于 的任意分布, 基于当前的隐藏状态。
HMMs的3个基本问题:
hmmlearn 是Python支持HMMs的包。原来是sklearn的一部分,后来由于接口不一致分成单独的包了。不过使用起来和sklearn的其他模型类似。
构造HMM model:
初始化的参数主要有 n_components , covariance_type , n_iter 。每个参数的作用我还没有研究。
通过 fit 方法。
输入是一个矩阵,包含拼接的观察序列concatenated sequences of observation (也就是samples),和序列的长度。
EM算法是背后拟合模型的算法。基于梯度优化的方法。通常会卡到一个局部极优值上。通常用户需要用不同的初始化跑多次 fit ,然后选择分数最高的模型。
分数通过 score 方法计算。
推导出的最优的隐藏状态可以调用 predict 方法获得。 predict 方法可以指定解码器算法。当前支持的有 viterbi (Vierbi algorithm)和 map (posteriori estimation)。
Q5: Python中的返回值问题!!!
首先,代码有误,你想调用的应该是
sorted([4,3,2,1])
reversed([4,3,2,1])
然后,你所说的reversed的返回值类型也不正确。
sorted返回的是list,reversed返回的是iterator。
list你应该很熟悉了。iterator和list是完全不同的东西。简单的说iterator只是提供一个接口,每次迭代可以产生一个值,到没有值为止。iterator在很多语言里面都有实现。在python里面主要用在for循环和list comprehension。
iterator和list/tuple/dict/set等容器的关系:
1.python内置的容器类几乎都实现了iterator接口。
显式获取某个容器的iterator可以调用iter函数:
l = [1,2,3,4]
i = iter(l)
//现在i就是一个list iterator。可以用来遍历l这个list.
i.next() # 1
i.next() # 2
//每一个iterator都必须实现next方法。并且在没有元素时抛出StopIteration异常。
在for语句和list comprehension中,都是隐式调用了这个函数。所以可以直接
for obj in some_container:
pass
2.某些容器可以通过iterator进行初始化,比如list
l = [1,2,3,4]
i = iter(l)
l2 = list(i)
最后,没有列表和列表对象这种说法。这两者一般都是指列表对象(instance of the type list)。如果你是想说列表类(the list type)本身,可以这样得到:
type([])
或者
[].__class__
隐式函数python的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于、隐式函数python的信息别忘了在本站进行查找喔。







