码迷,mamicode.com
首页 > 编程语言 > 详细

语言特性

时间:2015-04-27 18:19:43      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

1、魔方函数

http://www.rafekettler.com/magicmethods.html

2、with关键句

    class Excutor:
        def __enter__(self):
            set things up
            return thing
        def __exit__(self, type, value, traceback):
            tear things down

    with Excutor() as thing:
         some code

自动进行启动和收尾工作

Excutor()执行的结果是返回一个已经实现__enter__、__exit__函数的对象

3、迭代器与生成器

class yrange:
    def __init__(self, n):
        self.i = 0
        self.n = n

    def __iter__(self):
        return self

    def next(self):
        if self.i < self.n:
            i = self.i
            self.i += 1
            return i
        else:
            raise StopIteration()

迭代对象可以用于:

  • for x in iterator
  • sum, list以及itertool包中的函数

实现了__iter__函数,并且__iter__函数返回值可以执行next函数,且next出异常时抛出StopIteration

 

>>> def foo():
...     print "begin"
...     for i in range(3):
...         print "before yield", i
...         yield i
...         print "after yield", i
...     print "end"
...
>>> f = foo()
>>> f.next()
begin
before yield 0
0
>>> f.next()
after yield 0
before yield 1
1
>>> f.next()
after yield 1
before yield 2
2
>>> f.next()
after yield 2
end
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

生成器是通过函数形式自制可迭代对象,从而达到返回一系列值的目的

4、元类metaclass

不懂

5、动态创建类

>>> def choose_class(name):
…       if name == foo:
…           class Foo(object):
…               passreturn Foo     # 返回的是类,不是类的实例else:
…           class Bar(object):
…               passreturn Bar
…
>>> MyClass = choose_class(foo)
>>> print MyClass              # 函数返回的是类,不是类的实例
<class __main__.Foo>
>>> print MyClass()            # 你可以通过这个类创建类实例,也就是对象
<__main__.Foo object at 0x89c6d4c>
type 接受一个字典来为类定义属性,因此
>>> class Foo(A):
…       bar = True
可以翻译为:
>>> Foo = type(Foo, (A,), {bar:True})

 

语言特性

标签:

原文地址:http://www.cnblogs.com/johnchow/p/4460782.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!