资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

包含python隐式函数的词条

Python 有什么奇技淫巧

Python奇技淫巧

网站设计制作过程拒绝使用模板建站;使用PHP+MYSQL原生开发可交付网站源代码;符合网站优化排名的后台管理系统;成都网站设计、成都网站制作收费合理;免费进行网站备案等企业网站建设一条龙服务.我们是一家持续稳定运营了10年的成都创新互联网站建设公司。

当发布python第三方package时, 并不希望代码中所有的函数或者class可以被外部import, 在 __init__.py 中添加 __all__ 属性,

该list中填写可以import的类或者函数名, 可以起到限制的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 语句

知道具体原理, 我们可以自定义支持上下文管理协议的类, 类中实现 __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).从实现来看,这些参数都是可选的

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'

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

如何解决python2不能隐式继承

继承是所有开发语言的必修内容,而本文写的只是Python继承中的特殊之处,关于继承概念及内容可以自行百度(不装B,感觉百度挺好的)1.构造函数:

要说继承,先要说一下构造函数。Java要求是与类名相同并且无返回值,而Python则是强制要求命名为“__init__()”。

当创建类的对象时,会自动先调用构造函数,一般用于初始化。构造函数可以不写,那么程序会隐式自动增加一个空的构造函数。

2.继承写法:

(1).class 空格 类名称 括号内填写父类名 冒号具体写法如下class A:

def __init__(self):

pass

def print_class_name(self):

print "this is class A"

class B(A):

def __init__(self):

pass

if __name__ == "__main__":

class_b = B()

class_b.print_class_name()

上面代码首先定义了一个名为“A”的类,包含一个名为“print_class_name”的方法。然后,定义一个名为“B”的类,继承“A”,同时继承了“A”类的“print_class_name”的方法。

此时“A”类为“B”类的父类或者叫基类,“B”类是“A”类的子类,子类会继承父类的所有公共方法。

(2).意义:

一字记之曰“懒!”(感叹号不算字)我始终相信赖人才能推动科学进步。

言归正传,假如你要写一个老王类,包含年龄、性别等方法,后面还要写一个老王的儿子小王类,也有年龄、性别等方法?

class FatherWang:

def __init__(self, age=43, sex='man'):

self.a = age

self.s = sex

def age(self):

print self.a

def sex(self):

print self.s

class SonWang:

def __init__(self, age=13, sex='man'):

self.a = age

self.s = sex

def age(self):

print self.a

def sex(self):

print self.s

if __name__ == "__main__":

father = FatherWang(43, "man")

father.age()

father.sex()

son = SonWang(13, "man")

son.age()

son.sex()

你会发现两个类中有相同名称和功能的方法,这样写岂不是很重复很累?(尽管按键盘次数不算太多,我依然觉得很累)如果有继承就很好解决了。

class FatherWang:

def __init__(self, age=43, sex='man'):

self.a = age

self.s = sex

def age(self):

print self.a

def sex(self):

print self.s

class SonWang(FatherWang):

def __init__(self, age=13, sex='man'):

FatherWang.__init(age, sex)

if __name__ == "__main__":

father = FatherWang(43, "man")

father.age()

father.sex()

son = SonWang(13, "man")

son.age()

son.sex()

两者运行结果完全一样,但是使用继承方法却省了很多按键盘的次数。

3.经典类与新式类:

(1)经典类写法:

class A:

pass

(2)新式类写法:

class A(object):

pass

可以看出,新式类和经典类的区别在于,是否继承object这个基类。object是所有类的父类。所以之前不带“(object)”的写法,属于经典类写法,加上“(object)”就是新式类的写法。

(3).原因:这里我得吐槽一下Python的版本混乱。2.2版本之前只有经典类写法,这里有一个问题,代码如下?

class A:

pass

class B(object):

pass

a = A()

b = B()

print a.__class__

print type(a)

print "----------"

print b.__class__

print type(b)

结果为:

__main__.A

type 'instance'

----------

class '__main__.B'

class '__main__.B'

首先A类为经典类,B类为新式类。__class__属性和type()方法都是返回对象类型,那么问题来了,使用经典类的写法返回结果却不一致。因此在2.2版本之后出现了新式类来解决这个问题,自然,新式类和经典类还有更大的区别在后面说。另外在3.3版本中,无论使用哪种写法,python都会隐式的继承object,所以3.3版本不会再有经典类(在这里我只想问,早干什么去了!),但是鉴于3.3兼容性问题,貌似没有太多人用。

4.方法重写与方法重载

(1).方法重写:

class FatherWang:

def __init__(self, age=43, sex='man'):

self.a = age

self.s = sex

def age(self):

print self.a

def sex(self):

print self.s

def name(self):

print "Wang_yang"

class SonWang(FatherWang):

def __init__(self, age=13, sex='man'):

FatherWang.__init(age, sex)

def name(self):

print "Wang_xiaoming"

if __name__ == "__main__":

father = FatherWang(43, "man")

father.age()

father.sex()

father.name()

son = SonWang(13, "man")

son.age()

son.sex()

son.name()

比继承写法(2)中的代码相比,两个类分别多了同名的方法“name”,之前说过子类会继承父类的方法,那么这时候两个类有相同名字的方法,冲突了,怎么处理?

这个时候,就叫方法重写。可以理解为,子类的“name”方法把父类的“name”方法覆盖了,重新写了,所以调用子类的“name”方法时,会以子类的为准(尽管这种理解并不准确,但是可以很好解释“方法重写”这个名词,后面会讲到正确理解)。

注意下面的代码

class FatherWang:

def __init__(self, age=43, sex="man"):

self.a = age

self.s = sex

print "I am FatherWang"

def age(self):

print "Father age:"+str(self.a)

def sex(self):

print "Father sex:"+str(self.s)

class MotherLi:

def __init__(self, age=40, sex="woman"):

self.a = age

self.s = sex

print "I am MotherLi"

def age(self):

print "Mother age:"+str(self.a)

def sex(self):

print "Mother sex"+str(self.s)

class SonWang(FatherWang, MotherLi):

def __init__(self, age=13, sex="man"):

FatherWang.__init__(self, age, sex)

MotherLi.__init__(self, age, sex)

print "I am SonWang"

if __name__ == "__main__":

son = SonWang()

son.age()

son.sex()

执行结果:

I am FatherWang

I am MotherLi

I am SonWang

Father age:13

Father sex:man

在之前代码上稍作修改,另外增加了一个MotherLi的类,SonWang类继承了FatherWang类和MotherLi类。注意,这是经典类的写法。

首先,我们知道了python多继承的写法,就是在括号中上一个父类后面加个逗号,然后再写上下一个父类的名字:

class SonWang(FatherWang, MotherLi):

其次,FatherWang类和MotherLi类,都有名为age和sex方法,SonWang类为什么会继承FatherWang类的方法呢?那么把SonWang类的继承顺序改一下class SonWang(MotherLi, FatherWang):

就会发现继承的是MotherLi类的方法。

通过结果可知,是按照继承的顺序。

让我们把代码结构变得更发杂一些吧,我想会崩溃的,哈哈哈?

class Grandfather:

def __init__(self, age=73, sex="man"):

self.a = age

self.s = sex

print "I am Grandfather"

def age(self):

print "Grandfather age:"+str(self.a)

def sex(self):

print "Grandfather sex:"+str(self.s)

def Interesting(self):

print "Grandfather Interesting"

class Grandmother:

def __init__(self, age=70, sex="woman"):

self.a = age

self.s = sex

print "I am Grandmother"

def age(self):

print "Grandmother age:"+str(self.a)

def sex(self):

print "Grandmother sex:"+str(self.s)

def Interesting(self):

print "Grandmother Interesting"

class FatherWang(Grandfather, Grandmother):

def __init__(self, age=43, sex="man"):

self.a = age

self.s = sex

Grandfather.__init__(self, age, sex)

Grandmother.__init__(self, age, sex)

print "I am FatherWang"

def age(self):

print "Father age:"+str(self.a)

def sex(self):

print "Father sex:"+str(self.s)

class MotherLi(Grandfather, Grandmother):

def __init__(self, age=40, sex="woman"):

self.a = age

self.s = sex

Grandfather.__init__(self, age, sex)

Grandmother.__init__(self, age, sex)

print "I am MotherLi"

def age(self):

print "Mother age:"+str(self.a)

def sex(self):

print "Mother sex"+str(self.s)

def Interesting(self):

print "MotherLi Interesting"

class SonWang(FatherWang, MotherLi):

def __init__(self, age=13, sex="man"):

FatherWang.__init__(self, age, sex)

MotherLi.__init__(self, age, sex)

print "I am SonWang"

if __name__ == "__main__":

son = SonWang()

son.age()

son.sex()

son.Interesting()

执行结果:

I am Grandfather

I am Grandmother

I am FatherWang

I am Grandfather

I am Grandmother

I am MotherLi

I am SonWang

Father age:13

Father sex:man

Grandfather Interesting

话说,我自己都有点儿晕。简单来讲,就是儿子继承了老爸、老妈,然后老爸继承了爷爷、奶奶,妈妈继承了老爷、姥姥。(真是一大家子啊)通过执行结果可知,儿子类先找到老爸类,然后再找老爸类的第1个父类爷爷类,此时发现爷爷类没有父类了,那么执行初始化。然后还要继续找到老爸类的第2个父类奶奶类,此时发现奶奶类没有父类了,执行初始化。此时老爸类的所有父类都初始化完成,初始化自己。然后开始找妈妈类……那么为什么Interesting方法会使用爷爷类的呢?奶奶类、老爷类、姥姥类都有啊?首先儿子类没有Interesting方法,会先找第1个父类老爸类。发现老爸类也没有,再找老爸类的第1个父类,发现找到了,那么就直接调用不再往下找了。

结论:经典类的多继承,按照继承顺序查找。即,从左到右,从下到上的方式。注意,只有经典类是这样的!

(2).新式类的多继承:

class Grandfather(object):

def __init__(self, age=73, sex="man"):

self.a = age

self.s = sex

print "I am Grandfather"

def age(self):

print "Grandfather age:"+str(self.a)

def sex(self):

print "Grandfather sex:"+str(self.s)

def Interesting(self):

print "Grandfather Interesting"

class Grandmother(object):

def __init__(self, age=70, sex="woman"):

self.a = age

self.s = sex

print "I am Grandmother"

def age(self):

print "Grandmother age:"+str(self.a)

def sex(self):

print "Grandmother sex:"+str(self.s)

def Interesting(self):

print "Grandmother Interesting"

class FatherWang(Grandfather, Grandmother):

def __init__(self, age=43, sex="man"):

self.a = age

self.s = sex

Grandfather.__init__(self, age, sex)

Grandmother.__init__(self, age, sex)

print "I am FatherWang"

def age(self):

print "Father age:"+str(self.a)

def sex(self):

print "Father sex:"+str(self.s)

class MotherLi(Grandfather, Grandmother):

def __init__(self, age=40, sex="woman"):

self.a = age

self.s = sex

Grandfather.__init__(self, age, sex)

Grandmother.__init__(self, age, sex)

print "I am MotherLi"

def age(self):

print "Mother age:"+str(self.a)

def sex(self):

print "Mother sex"+str(self.s)

def Interesting(self):

print "MotherLi Interesting"

class SonWang(FatherWang, MotherLi):

def __init__(self, age=13, sex="man"):

FatherWang.__init__(self, age, sex)

MotherLi.__init__(self, age, sex)

print "I am SonWang"

if __name__ == "__main__":

son = SonWang()

son.age()

son.sex()

son.Interesting()

执行结果:

I am Grandfather

I am Grandmother

I am FatherWang

I am Grandfather

I am Grandmother

I am MotherLi

I am SonWang

Father age:13

Father sex:man

MotherLi Interesting

python中的if not 怎么用

python中的if not的用法说明如下:

1、if的语法为:if 条件为真:执行语句,而not是取反的意思。

2、从上面的解释可理解为:if not 条件为真:执行语句==if 条件不为真:执行语句。

3、举例:if n3:print "True",假如n=3,就打印“True”。如果加上not,即为if not n3:print “True”,就有:n=3,才会打印“True"。

扩展资料:

python中的“if not 1”:

if条件语句后面需要跟随bool类型的数据,即True或者False。然而,如果不是bool类型的数据,可以将其转换成bool类型的数据,转换的过程是隐式的。

在Python中,None、空列表[]、空字典{}、空元组()、0等一系列代表空和无的对象会被转换成False。除此之外的其它对象都会被转化成True。

在命令“if not 1”中,1便会转换为bool类型的True。not是逻辑运算符非,not 1则恒为False。因此if语句if not 1之下的语句,永远不会执行。

python 怎么样隐式函数调用

最常用的是在类定义的方法,给一个property的装饰器,可以安装调用属性的方式调用


标题名称:包含python隐式函数的词条
新闻来源:http://cdkjz.cn/article/hgejho.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220