1. Namespace and Scope
def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam spam = "nonlocal spam" def do_global(): global spam spam = "global spam" spam = "test spam" do_local() print("After local assignment:", spam) do_nonlocal() print("After nonlocal assignment:", spam) do_global() print("After global assignment:", spam) scope_test() print("In global scope:", spam) #result is: After local assignment: test spam After nonlocal assignment: nonlocal spam After global assignment: nonlocal spam In global scope: global spam
2. Class definition
class MyClass: """A simple example class""" i = 12345 def __init__(self, re=0, im=0): print('[ENTER] __init__') self.data=[] self.real = re self.image = im print('[EXIT] __init__') def f(self): return 'Hello world' if __name__ == '__main__': x = MyClass() print('x is [{0:f}, {1:f}]'.format(x.real, x.image)) y = MyClass(1.5, -2.7) print('y is [{0:f}, {1:f}]'.format(y.real, y.image))
3. Iterator
#! /usr/bin/env python3.0 class Reserve: def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def __next__(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] if __name__ == '__main__': print([x for x in Reserve('abcdefg')])
4. Generator
def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] >>> for char in reverse('golf'): ... print(char) ... f l o g
>>> sum(i*i for i in range(10)) # sum of squares 285