猫猫1 发表于 2017-4-30 12:00:12

Python Tutorial 笔记3

Class
  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(' __init__')
self.data=[]
self.real = re
self.image = im
print(' __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
if __name__ == '__main__':
print()

  4.  Generator

def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data
>>> for char in reverse('golf'):
...   print(char)
...
f
l
o
g
  

>>> sum(i*i for i in range(10)) # sum of squares
285

 
页: [1]
查看完整版本: Python Tutorial 笔记3