您的位置:首页 > 编程语言 > Python开发

Python语言特性(二)

2016-02-24 17:13 603 查看
6. Python中单下划线和双下划线

>>> class MyClass():
...     def __init__(self):
...             self.__superprivate = "Hello"
...             self._semiprivate = ", world!"
...
>>> mc = MyClass()
>>> print mc.__superprivate
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: myClass instance has no attribute '__superprivate'
>>> print mc._semiprivate
, world!
>>> print mc.__dict__
{'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'}


__foo__:一种约定,Python内部的名字,用来区别其他用户自定义的命名,以防冲突.

_foo:一种约定,用来指定变量私有.程序员用来指定私有变量的一种方式.

__foo:这个有真正的意义:解析器用
_classname__foo
来代替这个名字,以区别和其他类相同的命名.

7.
*args
and
**kwargs


*args
**kwargs
只是为了方便并没有强制使用它们.

当你不确定你的函数里将要传递多少参数时你可以用
*args
.例如,它可以传递任意数量的参数:

>>> def print_everything(*args):
for count, thing in enumerate(args):
...         print '{0}. {1}'.format(count, thing)
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage


相似的,
**kwargs
允许你使用没有事先定义的参数名:
>>> def table_things(**kwargs):
...     for name, value in kwargs.items():
...         print '{0} = {1}'.format(name, value)
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit


*args
**kwargs
可以同时在函数的定义中,但是
*args
必须在
**kwargs
前面.

当调用函数时你也可以用
*
**
语法.例如:

>>> def print_three_things(a, b, c):
...     print 'a = {0}, b = {1}, c = {2}'.format(a,b,c)
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)

a = aardvark, b = baboon, c = cat


就像你看到的一样,它可以传递列表(或者元组)的每一项并把它们解包.注意必须与它们在函数里的参数相吻合.当然,你也可以在函数定义或者函数调用时用*.

8. 面向切面编程AOP和装饰器

装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志、性能测试、事务处理等。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数功能本身无关的雷同代码并继续重用。概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。

例子:怎么做才能让一个函数同时用两个装饰器,像下面这样

@makebold
@makeitalic
def say():
return "Hello"


期望的结果:

<b><i>Hello</i></b>


答案:

def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped

def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped

@makebold
@makeitalic
def hello():
return "hello world"

print hello() ## returns <b><i>hello world</i></b>


9. Python中重载

python 不需要函数重载

10.
__new__
__init__
的区别


__new__
是一个静态方法,而
__init__
是一个实例方法.
__new__
方法会返回一个创建的实例,而
__init__
什么都不返回.
只有在
__new__
返回一个cls的实例时后面的
__init__
才能被调用.
当创建一个新实例时调用
__new__
,初始化一个实例时用
__init__
.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: