python 模块 类 函数装饰器如何装饰引用模块中的函数

name = 'world'
变量是代表某个值的名字
def hello(name):
return 'hello' + name
hello('word)
hello word
函数通过def关键字、函数名和可选的参数列表定义。
是可以调用的,它执行某种行为并且返回一个值。
函数内部也可以定义函数
def outer():
def inner():
print x # 1
&& outer()
作用域&生存周期
def func(x):
print 'x is', x
print locals()
&& x is 50
{'x': 50}
&& print x
Traceback (most recent call last):
NameError: name 'x' is not defined
函数会创建一个新的作用域(命名空间)。
函数的命名空间随着函数调用开始而开始,结束而销毁
g = 'global variable'
&& print globals()
{'g': 'global variable',
'__builtins__': &module '__builtin__' (built-in)&,
'__file__': 'test.py',
'__package__': None,
'func': &function func at 0x&,
'__name__': '__main__',
'__doc__': None}
def foo():
g = 'test'
print 'g is', g
print locals()
print globals()
{'g': 'test'}
{'g': 'global variable',
'__builtins__': &module '__builtin__' (built-in)&,
'__file__': 'test.py',
'__package__': None,
'func': &function func at 0x&,
'__name__': '__main__',
'__doc__': None}
&& print g
global variable
在函数内部遇到变量的时候会有现在自己的命名空间里找
猜一下段代码会执行的结果是什么
g = '我已经定义了'
def foo():
g = '我重新定义了'
函数有两种参数
def foo(x, y=0):
return x - y
python 中一切都是对象
函数和python中其他一样都是对象
In [7]: class A(object):
Out[8]: __main__.A
In [9]: type(A)
Out[9]: type
In [10]: def foo():
In [11]: type(foo)
Out[11]: function
In [12]: A.__class__
Out[12]: type
In [13]: foo.__class__
Out[13]: function
In [14]: a = 1
In [15]: a.__class__
Out[15]: int
# 类 是对象
In [16]: issubclass(A.__class__, object)
Out[16]: True
# 变量 是对象
In [17]: issubclass(a.__class__, object)
Out[17]: True
# 函数 是对象
In [18]: issubclass(foo.__class__, object)
Out[18]: True
所以函数也可以作为参数传递给其它函数,也可以被当做返回值返回
def add(x, y):
return x + y
def apply(func):
return func
&& a = apply(add)
&& type(a)
&type 'function'&
&& a(1, 2)
def make_adder(a):
def adder(b):
return b + a
return adder
add = make_adder(5)
&function adder at 0x&
adder 就是一个闭包
也可以说 make_adder 指向一个闭包
或者说 make_add 是闭包的工厂函数
闭包可以认为是一个内层函数(adder),由一个变量指代,而这个变量相对于外层包含它的函数而言,是本地变量
嵌套定义在非全局作用域里面的函数能够记住它在被定义的时候它所处的封闭命名空间
闭包只是在形式和表现上像函数,但实际上不是函数。函数是一些可执行的代码,这些代码在函数被定义后就确定了,不会在执行时发生变化,所以一个函数只有一个实例。闭包在运行时可以有多个实例,不同的引用环境和相同的函数组合可以产生不同的实例。
对一个已有的模块做一些“修饰工作”,所谓修饰工作就是想给现有的模块加上一些小装饰(一些小功能,这些小功能可能好多模块都会用到),但又不让这个小装饰(小功能)侵入到原有的模块中的代码里去
def my_decorator(func):
def wrapper():
print &Before the function runs&
print &After the function runs&
return wrapper
def my_func():
print &I am a stand alone function&
&& my_func()
I am a stand alone function
# 然后,我们在这里装饰这个函数
# 将函数传递给装饰器,装饰器将动态地将其包装在任何想执行的代码中,然后返回一个新的函数
&& my_func = my_decorator(my_func)
&& my_func()
Before the function runs
I am a stand alone function
After the function runs
# 也可以这么写
@ my_decorator
def my_func():
print &I am a stand alone function&
&& my_func()
Before the function runs
I am a stand alone function
After the function runs
装饰器是设计模式中()的python实现
多个装饰器
装饰器可以嵌套使用
def bread(func):
def wrapper():
print &&/''''''\&&
print &&\______/&&
return wrapper
def ingredients(func):
def wrapper():
print &#tomatoes#&
print &~salad~&
return wrapper
def sandwich(food=&--ham--&):
print food
#嵌套两个装饰器
&& sandwich = bread(ingredients(sandwich))
&& sandwich()
# outputs:
&/''''''\&
#tomatoes#
&\______/&
更简单的写法
@ingredients
def sandwich(food=&--ham--&):
print food
装饰器的顺序是很重要的
@ingredients
def sandwich(food=&--ham--&):
print food
# outputs:
#tomatoes#
&/' ' ' ' ' '\&
&\______/&
Decorator 的本质
首先看一下这段代码
def deco(fn):
print &I am %s!& % fn.__name__
def func():
I am func!
# 没有执行func 函数 但是 deco 被执行了
@decorator
def func():
其解释器会解释成下面这样的语句:
func = decorator(func)
其实就是把一个函数当参数传到另一个函数中,然后再回调
但是值得注意的是装饰器必须返回一个函数给func
回到刚才的例子
def my_decorator(func):
def wrapper():
print &Before the function runs&
print &After the function runs&
return wrapper
def my_func():
print &I am a stand alone function&
&& my_func = my_decorator(my_func)
&& my_func()
Before the function runs
I am a stand alone function
After the function runs
my_decorator(my_func)返回了wrapper()函数,所以,my_func其实变成了wrapper的一个变量,而后面的my_func()执行其实变成了wrapper()
比如:多个decorator
@decorator_one
@decorator_two
def func():
func = decorator_one(decorator_two(func))
比如:带参数的decorator:
@decorator(arg1, arg2)
def func():
func = decorator(arg1,arg2)(func)
带参数的装饰器
首先看一下, 如果被装饰的方法有参数
def a_decorator(method_to_decorate):
def wrapper(self, x):
print 'x is %s' % x
method_to_decorate(self, x)
return wrapper
class A(object):
def __init__(self):
self.b = 42
@a_decorator
def number(self, x):
print &b is %s& % (self.b + x)
a.number(-3)
通常我们都使用更加通用的装饰器,可以作用在任何函数或对象方法上,而不必关系其参数 使用
def a_decorator(method_to_decorate):
def wrapper(*args, **kwargs):
print '****** args ******'
print args
print kwargs
method_to_decorate(*args, **kwargs)
return wrapper
@a_decorator
def func():
****** args ******
@a_decorator
def func_with_args(a, b=0):
return a + b
func_with_args(1, b=2)
****** args ******
{'b': 2}
上边的示例是带参数的被装饰函数
现在我们看一下向装饰器本身传递参数
向装饰器本身传递参数
再看一下这段代码
def deco(fn):
print &I am %s!& % fn.__name__
def func():
I am func!
没有执行func 函数 但是 deco 被执行了
其解释器会解释成下面这样的语句:
func = deco(func)
装饰器必须使用函数作为参数,你不能直接传递参数给装饰器本身
如果想传递参数给装饰器,可以 声明一个用于创建装饰器的函数
# 我是一个创建装饰器的函数
def decorator_maker():
print &I make decorators!&
def my_decorator(func):
print &I am a decorator!&
def wrapped():
print &I am the wrapper around the decorated function. &
return func()
print &As the decorator, I return the wrapped function.&
return wrapped
print &As a decorator maker, I return a decorator&
return my_decorator
# decorator_maker()返回的是一个装饰器
new_deco = decorator_maker()
I make decorators!
As a decorator maker, I return a decorator
# 使用装饰器
def decorated_function():
print &I am the decorated function&
decorated_function = new_deco(decorated_function)
decorated_function()
I make decorators!
As a decorator maker, I return a decorator
I am a decorator!
As the decorator, I return the wrapped function.
I am the wrapper around the decorated function.
I am the decorated
decorated_function = new_deco(decorated_function)
# 等价于下面的方法
def func():
print &I am the decorated function&
@decorator_maker()
def func():
print &I am the decorated function&
my_decorator(装饰器函数)是decorator_maker(装饰器生成函数)的内部函数
所以可以使用把参数加在decorator_maker(装饰器生成函数)的方法像装饰器传递参数
# 我是一个创建带参数装饰器的函数
def decorator_maker_with_arguments(darg1, darg2):
print &I make decorators! And I accept arguments:&, darg1, darg2
def my_decorator(func):
print &I am a decorator! Somehow you passed me arguments:&, darg1, darg2
def wrapped(farg1, farg2):
print &I am the wrapper around the decorated function.&
print &I can access all the variables&, darg1, darg2, farg1, farg2
return func(farg1, farg2)
print &As the decorator, I return the wrapped function.&
return wrapped
print &As a decorator maker, I return a decorator&
return my_decorator
@decorator_maker_with_arguments(&deco_arg1&, &deco_arg2&)
def decorated_function_with_arguments(function_arg1, function_arg2):
print (&I am the decorated function and only knows about my arguments: {0}&
& {1}&.format(function_arg1, function_arg2))
decorated_function_with_arguments('farg1', 'farg2')
I make decorators! And I accept arguments: deco_arg1 deco_arg2
As a decorator maker, I return a decorator
I am a decorator! Somehow you passed me arguments: deco_arg1 deco_arg2
As the decorator, I return the wrapped function.
I am the wrapper around the decorated function.
I can access all the variables deco_arg1 deco_arg2 farg1 farg2
I am the decorated function and only knows about my arguments: farg1 farg2
这里装饰器生成函数内部传递参数是闭包的特性
使用装饰器需要注意
装饰器是Python2.4的新特性
装饰器会降低代码的性能
装饰器仅在Python代码导入时被调用一次,之后你不能动态地改变参数.当你使用&import x&,函数已经被装饰
最后Python2.5解决了最后一个问题,它提供functools模块,包含functools.wraps.这个函数会将被装饰函数的名称,模块,文档字符串拷贝给封装函数
def foo():
print &foo&
print foo.__name__
#outputs: foo
# 但当你使用装饰器
def bar(func):
def wrapper():
print &bar&
return func()
return wrapper
def foo():
print &foo&
print foo.__name__
#outputs: wrapper
&functools& 可以修正这个错误
import functools
def bar(func):
# 我们所说的 &wrapper&, 封装 &func&
@functools.wraps(func)
def wrapper():
print &bar&
return func()
return wrapper
def foo():
print &foo&
# 得到的是原始的名称, 而不是封装器的名称
print foo.__name__
#outputs: foo
class myDecorator(object):
def __init__(self, func):
print &inside myDecorator.__init__()&
self.func = func
def __call__(self):
self.func()
print &inside myDecorator.__call__()&
@myDecorator
def aFunction():
print &inside aFunction()&
print &Finished decorating aFunction()&
aFunction()
# output:
# inside myDecorator.__init__()
# Finished decorating aFunction()
# inside aFunction()
# inside myDecorator.__call__()
我们可以看到这个类中有两个成员:
一个是__init__(),这个方法是在我们给某个函数decorator时被调用,所以,需要有一个func的参数,也就是被decorator的函数。
一个是__call__(),这个方法是在我们调用被decorator函数时被调用的
**如果decorator有参数的话,init() 就不能传入func了,而fn是在__call__的时候传入**
class myDecorator(object):
def __init__(self, arg1, arg2):
self.arg1 = arg2
def __call__(self, func):
def wrapped(*args, **kwargs):
return self.func(*args, **kwargs)
return wrapped
装饰器示例
def counter(func):
记录并打印一个函数的执行次数
def wrapper(*args, **kwargs):
wrapper.count = wrapper.count + 1
res = func(*args, **kwargs)
print &{0} has been used: {1}x&.format(func.__name__, wrapper.count)
return res
wrapper.count = 0
return wrapper
装饰器做缓存
from functools import wraps
def memo(fn):
cache = {}
miss = object()
@wraps(fn)
def wrapper(*args):
result = cache.get(args, miss)
if result is miss:
result = fn(*args)
print &{0} has been used: {1}x&.format(fn.__name__, wrapper.count)
cache[args] = result
return result
return wrapper
def fib(n):
return fib(n - 1) + fib(n - 2)
15言和知性中用到的缓存
def cache_for(duration):
def deco(func):
@wraps(func)
def fn(*args, **kwargs):
key = pickle.dumps((args, kwargs))
value, expire = func.func_dict.get(key, (None, None))
now = int(time.time())
if value is not None and expire & now:
return value
value = func(*args, **kwargs)
func.func_dict[key] = (value, int(time.time()) + duration)
return value
return deco
统计代码运行时间
def timeit(fn):
@wraps(fn)
def real_fn(*args, **kwargs):
if mon['ENVIRON'] == 'PRODUCTION':
return fn(*args, **kwargs)
_start = time.time()
#app.logger.debug('Start timeit for %s' % fn.__name__)
result = fn(*args, **kwargs)
_end = time.time()
_last = _end - _start
app.logger.debug('End timeit for %s in %s seconds.' %
(fn.__name__, _last))
return result
return real_fn
Python本身提供了一些装饰器:property,staticmethod
阅读(...) 评论()
Copyright &2011 Goodspeed ChengPython(38)
一:函数装饰函数
def wrapFun(func):
def inner(a, b):
print('function name:', func.__name__)
r = func(a, b)
return inner
def myadd(a, b):
return a + b
print(myadd(2, 3))
二:函数装饰类
def wrapClass(cls):
def inner(a):
print('class name:', cls.__name__)
return cls(a)
return inner
@wrapClass
class Foo():
def __init__(self, a):
self.a = a
def fun(self):
print('self.a =', self.a)
m = Foo('xiemanR')
三:类装饰函数
class ShowFunName():
def __init__(self, func):
self._func = func
def __call__(self, a):
print('function name:', self._func.__name__)
return self._func(a)
@ShowFunName
def Bar(a):
print(Bar('xiemanR'))
四:类装饰类
class ShowClassName(object):
def __init__(self, cls):
self._cls = cls
def __call__(self, a):
print('class name:', self._cls.__name__)
return self._cls(a)
@ShowClassName
class Foobar(object):
def __init__(self, a):
self.value = a
def fun(self):
print(self.value)
a = Foobar('xiemanR')
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:99484次
积分:1778
积分:1778
排名:千里之外
原创:92篇
转载:12篇
评论:22条
(6)(18)(30)(10)(6)(1)(2)(6)(11)(1)(1)(1)(1)(3)(8)Python装饰器 - The Dawn. - ITeye博客
博客分类:
编写自定义装饰器有许多方法,但最简单和最容易理解的方法是编写一个函数,返回封装原始函数调用的一个子函数。
通用的模式如下。
def my_decorator(function):
def _my_decorator(*args, **kw):
#在调用实际函数之前做些填充工作
res = function(*args, **kw)
#做完某些填充工作之后
return res
#返回子函数
return _my_decorator
当装饰器需要参数时,必须使用第二级封装。
def my_decorator(arg1, arg2):
def _my_decorator(function):
def __my_decorator(*args, **kw):
res = function()
return res
return __my_decorator
return _my_decorator
引用因为装饰器在模块第一次被读取时由解释程序装入,所以它们的使用必须受限于总体上可以应用的封装器。如果装饰器与方法的类或所增强的函数签名绑定,它应该被重构为常规的可调用对象,从而避免复杂性。在任何情况下,当装饰器处理API时,一个好的方法是将它们聚集在一个易于维护的模块中。
参数检查:
def check_param_isvalid():
def check(method):
def check_param(*args,**kwargs):
for a in args:
assert isinstance(a, int),"arg %r does not match %s" % (a,int)
assert a & 100000,"arg %r must gt 100000" % a
return method(*args, **kwargs)
return check_param
return check
@check_param_isvalid()
def foo(*args):
print args
foo(000)
缓存:
import time
import hashlib
import pickle
cache = {}
def is_obsolete(entry, duration):
return time.time() - entry['time'] & duration
def computer_key(function, args, kw):
key = pickle.dumps((function.func_name, args, kw))
return hashlib.sha1(key).hexdigest()
def memoize(duration=30):
def _memoize(function):
def __memoize(*args, **kw):
key = computer_key(function, args, kw)
if key in cache and not is_obsolete(cache[key], duration):
print 'wo got a winner'
return cache[key]['value']
result = function(*args, **kw)
cache[key] = {'value':result,'time':time.time()}
return result
return __memoize
return _memoize
@memoize()
def very_complex_stuff(a,b):
return a + b
print very_complex_stuff(2,2)
class User(object):
def __init__(self, roles):
self.roles = roles
class Unauthorized(Exception):
def protect(role):
def _protect(function):
def __protect(*args, **kw):
user = globals().get('user')
if user is None or role not in user.roles:
raise Unauthorized("I won't tell you")
return function(*args, **kw)
return __protect
return _protect
tarek = User(('admin', 'user'))
bill = User(('user',))
class MySecrets(object):
@protect('admin')
def waffle_recipe(self):
print 'use tons of butter!'
these_are = MySecrets()
user = tarek
these_are.waffle_recipe()
user = bill
these_are.waffle_recipe()
上下文提供者:
from threading import RLock
lock = RLock()
def synchronized(function):
def _synchronized(*args, **kw):
lock.acquire()
return function(*args, **kw)
lock.release()
return _synchronized
@synchronized
def thread_safe():
print 'haha'
thread_safe()
补充:
参考资料:
Python高级编程
浏览: 132935 次
来自: 北京
这个程序有bug。一、函数示例:
  1、为什么使用函数之模块化程序设计:
    不使用模块程序设计的缺点:
    1、体系结构不清晰,可主读性差;
    2、可扩展性差;
    3、程序冗长;
  2、定义函数:
    def fun(args):
      '描述信息'
      函数体
    return 返回值
  定义函数的三种形式:
    无参函数
def foo():
print('in the foo')
有参函数:
def bar(x,y):
print('in the bar')
def func():
空函数的应用示例:
def put():
def get():
def auth():
3、调用函数:三种形式:语句形式:
def foo():
print('in the foo')
表达式形式:
def my_max(x,y)
res = my_max(1,2)
res = 10 * my_max(1,2)
作为另外一个函数的参数:my_max(1,my_max(2,3)): #先比较2与3的最大值,再与1作比较;    
4、函数的返回值三种形式:
不返回函数:
def foo():
print('in the foo')
res = foo()
print(res)
返回一个函数:
def foo():
res = foo()
print(res)
返回多个:
def foo():
return 1,'s',[1,2,3]
res = foo()
print(res)
5、函数的参数:
def func(x,y): #形参在调用时才真正占用内存空间,调用结束则释放内存空间;
fund(1,2) #实参真实占用内存空间;
def func(x,y):
if type(x) is int and type(y) is int:
return x+y
func(1,'a')
def func(x,y): #使用文档注释来提醒用户输入参数类型;
return x+y
func(1,'a')
def func(x:int,y:int)-&int: #只是一个提示作用;
print(func.__annotations__)
从实参的角度,
按位置传值:
def foo(x,y):
print(x,y)
按关键字传参:key = value
def foo(x,y):
print(x,y)
foo(y=2,x=1) #优点:不用按位置来输入参数;
针对同一个形参,要么按照位置要么按照关键字为形参传值;关键字参数必须写到位置参数的右边;
如:foo(1,x=1,y=2) 此方法会报错;
从形参的角度:位置参数,默认参数,可变长参数*args;**
按位置定义的形参:
def foo(x,y,z): #位置参数;也就是必传值参数;
foo(1,2,3)
foo(y=2,x=1,z=3)
按默认参数的形参:
def foo(x,y=1): #y就是默认参数;但也可以去赋值;默认参数建议不要使用列表或字典等可变类型;必须放在默认参数之后;
按可变长参数的形参:
def foo(x,y=1,*args): #可变长参数必须放在位置参数与默认参数的后面;此情况一般不使用位置参数;
print(args)
foo(1,2,3,4,54,6,3,y=2) #错
foo(1,2,3,4,54,y=2,3,5) #错
foo(1,2,3,4,54,6,3) #对
def foo(x,y,*args):
print(*args)
l=['a','b']
foo(1,2,*1) #*args的形式就等于1,2,3,4,5 解包;
def foo(x,y,z):
# foo(1,2,3)
def foo(x,**kwargs):
print(kwargs)
foo(1,y=3,z=2)
dic = {'a':1,'b':2}
foo(1,**dic) #foo(1,a=1,b=2)
def foo(x,y,z):
print(x,y,z)
foo(**{'a':1,'b':2,'c':3}) #foo(a=1,b=2,c=3),要把a,b,c改成x,y,z
foo(**{'x':1,'y':2,'z':3})
注:位置参数 -& 默认参数,*args, **kwargs
1、*args 相当于展开按照位置的方式去写;
2、**kwargs 相当于把kwargs按照关键字的方式去写;
6、函数是第一类对象的意思就是函数可以被当作数据来传递;
def func()
print('in the fun')
函数可作为参数:高阶函数:
def foo(x):
返回值可以是函数:
##########################################
可以作为容器类型的元素:
func_dic={
'func':func
func_diuc['func']()
7、函数的嵌套:分为两种:
嵌套的调用:
def my_max1(a,b,c,d):
res1=my_max(a,b)
res2=my_max(res1,c)
res3=my_max(res2,d)
return res3
def my_max(x,y):
print(my_max1(100,2,-1,5))
嵌套的定义: python支持静态的嵌套域;
#def f3():
# print(x)
#return f3
闭包函数:
from urllib request import urlopen #用来爬网页;
def page(url):
def get():
return urlopen(url).read()
return get
baidu = page('http//')
python = page('http://www.python.org')
二、装饰器
装饰器:在遵循下面的两个原则 的前提下为被修饰者添加新功能;
函数功能的扩展原则:
1、一定不能修改源代码;
2、不能改变函数的调用方式;
装饰器本身是一个函数,被装饰的也是一个函数;
def index():
print('in the ndex')
@timer #表示方法:index = timer(index)
def index():
print('in the ndex')
装饰器的叠加:
@deco1 #func1 = deco1(index) --& func2=deco2(func1) --& index= deco3(func2)====&index=deco3(deco2(deco1(index)))
def index():
print('in the ndex')
from urllib request import urlopen #用来爬网页;
import time
def timer(func):
def wrapper():
print('in the wrapper--&start')
start_time=time.time()
print('in the wrapper--&stop')
return wrapper
@timer #表示方法:index = timer(index)
def index():
print('in the ndex')
from urllib request import urlopen #用来爬网页;
import time
def timer(func):
def wrapper(*args,**kwargs): #一定不要写死;
print('in the wrapper--&start')
start_time=time.time()
res=func(*args,**kwargs) #home('tom',msg='xxxx')--&home(user,msg) *与位置等同
func(msg) #运行最原始的index -& index(msg)
print('in the wrapper--&stop')
return res
return wrapper
@timer #表示方法:index = timer(index)
def index(msg):
print('in the ndex',msg)
def home(user,msg):
print('in the home %s %s',%(user,msg)
return 1 #返回值要写在wrapper中
index('hello world')
home('tom',msg='xxxx')
什么是模块:
模块就是一个包含了python定义和声明的文件;文件名就是模块名字加上.py的后缀;
模块只会被导入一次,第一次会导入到内存中,第二次再导入直接去内存调用
模块的导入:
第一次导入模块三个事件:
1、创建新的作用域;
2、在该作用域内执行顶级代码;
3、得到一个模块名,绑定到该模块内的代码;
为模块起别名:
import spam as sm
print(sm.money)
from spam import read1 as rea
导入多个模块:
import ms,spam,re
from spam import (read1,change)可写入多行;
导入模块的另外一种形式:
from .. import ..
from spam import read1
从那来就从哪执行,与调用的位置无关;
将module中所有非下划线开头的名称导入:
from module import *
__all__ = ['money','read1']
模块不支持重载;要加载需要重启程序;
把文件当做和脚本执行__name__等于'__main__';
print(__name__)
把spam.py文件当作模块去使用__name__等于'spam'
if __name__ = '__main__':
print('文件被当作脚本执行时触发的代码')
可以控制python代码在不同场景下运行的代码;
模块路径的查找: import sys sys.path
路径的查找先找内置的路径,再找其他的路径;
1、当前目录;
2、python path
3、安装时依赖的一些目录;
sys.path.append(r'/test')
#当前目录有效;
r表示对特殊字符的转义; sys.path.insert(0,r'/test') #从0的位置插入;
导入模块时,先从内建中找相同的模块名,找不到就去sys.path中找;
dir() 不会列举出内建模块的名字;import builtinsdir(builtins)
包: 包是一种通过使用‘.模块名’来组织python模块名称空间的方式。
无论是import形式还是from...import形式,凡是在导入语句中(而不是在使用时)遇到带点的,都要第一时间提高警觉:这是关于包才有的导入语法
包的本质就是一个包含__init__.py文件的目录。
from ... import ...
需要注意的是from后import导入的模块,必须是明确的一个不能带点,否则会有语法错误,如:from a import b.c是错误语法
__init__.py文件
不管是哪种方式,只要是第一次导入包或者是包的任何其他部分,都会依次执行包下的__init__.py文件(我们可以在每个包的文件内都打印一行内容来验证一下),这个文件可以为空,但是也可以存放一些初始化包的代码。
from glance.api import *
在讲模块时,我们已经讨论过了从一个模块内导入所有*,此处我们研究从一个包导入所有*。
此处是想从包api中导入所有,实际上该语句只会导入包api下__init__.py文件中定义的名字,我们可以在这个文件中定义__all___:
#在__init__.py中定义
def func():
print('from api.__init.py')
__all__=['x','func','policy']
此时我们在于glance同级的文件中执行from glance.api import *就导入__all__中的内容(versions仍然不能导入)。
from glance.api import *
只会运行api下的__init__.py文件;
在api\__init__.py中输入:
__all__ = ['policy','versions']
import只能导入内建与第三方的模块,否则会出错;
四、内置函数
内置函数解释:
# !/usr/bin/env python
# -*- coding:utf-8 -*-
#返回数字的绝对值。 参数可以是整数或浮点数。 如果参数是复数,则返回其大小。
print(abs(-1.11))
#传入一个可被循环的元素,如果这个元素中有一个为False则都为假
# 0 空值 False 都为假
print(all([1,2,3]))
#与all相反,只有一个为真,则为真;
print(any([0,2,False]))
#这个函数跟repr()函数一样,返回一个可打印的对象字符串方式表示。当遇到非ASCII码时
#就会输出\x,\u或\U等字符来表示。与Python 2版本里的repr()是等效的函数。
print(ascii("dsads"),ascii(66),ascii('b\23'))
#将十进制转换为二进制;
print(bin(10))
#返回布尔值,即True或False之一,如果参数为false或省略,则返回F 否则返回True。
print(bool(1))
#根据传入的参数创建一个新的字节数组
#如果传入字符串必须给出编码
print(bytearray('你好','utf-8'))
#当source参数是一个可迭代对象,那么这个对象中的元素必须符合大于0 小于256
print(bytearray([256,1,2]))
#返回一个的“bytes”对象,返回bytes类型
bytes('中文','utf-8')
#检查对象是否可以被调用
def func():
print(callable(func))
#返回整数所对应的Unicode字符,chr(97)返回字符串'a',而chr(8364)返回字符串'EUR'。
print(chr(126))
#是用来指定一个类的方法为类方法,类方法可以不实例化直接调用
@classmethod
def B(cls,arg1,):
print(arg1)
#将源编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。
#源可以是正常字符串,字节字符串或AST对象。
expr = "5+5-1"
obj = compile(expr,"","eval")
print(eval(obj))
#返回值为real + imag * j的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。
print(complex(1, 2))
print(complex(1))
print(complex("1+2j"))
# 参数是一个对象和一个字符串。 该字符串必须是对象属性之一的名称。
def a1(self):
print("a1")
def a2(self):
print("a2")
print(dir(obj))
delattr(obj, "a1")
print(dir(obj))
#dir 返回对象中的方法
strs="aaa"
print(dir(strs))
#返回两个数值的商和余数
print(divmod(7,3))
#用于遍历序列中的元素以及它们的下标
print(enumerate([1,2,3]))#返回的是可迭代的对象
for i,j in enumerate(('A','B','C')):
print(i,j)
#将字符串str当成有效的表达式来求值并返回计算结果。
print(eval("1+2+3"))
print(eval("False or True"))
#字符串str当成动态语句块执行并返回结果
exec('a=1+2+3')
#使用指定方法(方法,函数),过滤可迭代对象的元素
def add(arg):
return arg & 3
for i in filter(add,[1,2,3,4,5]):
print(float(11))
#格式化显示 更多方法请参考官方说明
print('{:,.2f}'.format(111111))
#根据传入的参数创建一个新的不可变集合
a = frozenset([1,2,3,4,5])
#获取对象的属性值
class A():
def __init__(self,):
self.name = "123"
print(getattr(b,'name'))
#返回当前作用域内的全局变量和其值组成的字典
print(globals())
#检查对象是否含有属性
class A():
def __init__(self,):
self.name = "123"
print(hasattr(b,'name'))
#哈希值计算
#在当前环境中是唯一的
print(hash('Hello'))
def funcs(args):
Function description
:param args: args = list
print(help(funcs))
#转换16进制
print(hex(44))
#显示对象的标识符
print(id("123"))
#input标准输入
s = input("user name:")
#int返回整数
print(int(1.2))
print(int("2"))
#判断对象是否是类或者类型元组中任意类元素的实例
print(isinstance("1",int))
print(isinstance(1.1,(int,float)))
#判断类是否是另外一个类或者类型元组中任意类元素的子类
print(dir(str))
print(issubclass(bytearray,str))
print(issubclass(bool,int))
#根据传入的参数创建一个新的可迭代对象
a = iter('12345')
print(next(a))
print(next(a))
#返回对象的长度len
a = [1,2,3,4]
print(list("abcd"))
#返回当前作用域内的局部变量和其值组成的字典
print(locals())
print(locals())
#使用指定方法去作用传入的每个可迭代对象的元素,生成新的可迭代对象
def add(x):
return x+100
lists = [1,2,3,4]
for i in map(add,lists):
#max:返回最大值
print(max(1,2,3))
print(max([1,2,3,4]))
#在进行切片并赋值数据时,不需要重新copy原列表数据,可以直接映射原数据内存;
s = memoryview(b'abcd')
print(s[1])
#返回最小值
print(min(1,2,3))
print(min([2,3]))
#返回可迭代对象中的下一个元素值
a = iter('1234')
print(next(a))
#创建一个新的object对象(新式类)
class B(object):
#转化成8进制数字符串
print(oct(10))
#open文件操作
file = open('test.txt',encoding="utf-8")
#ord:返回Unicode字符对应的整数
print(ord("A"))
print(pow(2,3))
#property:标示属性的装饰器
#类中使用具体方法请百度,或者等待后续更新
#range:根据传入的参数创建一个新的range对象
range(1,10)
"""repr()函数得到的字符串通常可以用来重新获得该对象,repr()的输入对python比较友好。
通常情况下obj==eval(repr(obj))这个等式是成立的。"""
obj='Python'
print(eval(repr(obj)))
a = reversed([1,2,3,4,5])
print(list(a))
#round:对浮点数进行四舍五入求值
print(round(1.5))
#set 转换成集合
print(set([1,2,3]))
#setattr:设置对象的属性值
class A():
def __init__(self,age):
self.age = age
print(s.age)
setattr(s,'age',22)
print(s.age)
#根据传入的参数创建一个新的切片对象
c1 = slice(3)
c2 = slice(2,4)
c3 = slice(0,5,2)
s = [1,2,3,4,5,6]
print(s[c1])
print(s[c2])
print(s[c3])
#排序,返回一个新的列表默认按字符ascii码排序
a = [4,3,2,1,7]
print(sorted(a))
#标示方法为静态方法的装饰器
class B(object):
def __init__(self,age):
self.age = age
@staticmethod
def hello(args):
print(args)
B.hello("Hello World")
#字符串类型
print(str(123))
print(sum([1,2,3,4]))
#根据传入的参数创建一个新的子类和父类关系的代理对象
class A(object):
def __init__(self):
print("我是 A Clase")
class B(A):
def __init__(self):
print("我是 B Class")
super().__init__()
tuple([1,2,3,4])
#type 返回对象的类型
print(type([1]))
print(type("1"))
#返回当前作用域内的局部变量和其值组成的字典,或者返回对象的属性列表
def func():
print(vars())
print(vars())
#聚合传入的每个迭代器中相同位置的元素,返回一个新的元组类型迭代器
list1 = [1,2,3]
list2 = ["A","B","C","D"]
print(zip(list1,list2))
for i in zip(list1,list2):
#__import__:动态导入模块
__import__
阅读(...) 评论()

我要回帖

更多关于 python 模块函数列表 的文章

 

随机推荐