1 class中的函数
1.1 __init__()是类的初始化函数
1.2 __str__()是类用来转化为string的函数。这样 print 打印类对象的时候,就可以正确打印了。
1.3 eg 生成一团随机点集的例子
# Particle class example used to simulate diffusion of molecules
import simplegui
import random
# global constants
WIDTH = 600
HEIGHT = 400
PARTICLE_RADIUS = 5
COLOR_LIST = ["Red", "Green", "Blue", "White"]
DIRECTION_LIST = [[1,0], [0, 1], [-1, 0], [0, -1]]
# definition of Particle class
class Particle:
# initializer for particles
def __init__(self, position, color):
self.position = position
self.color = color
# method that updates position of a particle
def move(self, offset):
self.position[0] += offset[0]
self.position[1] += offset[1]
# draw method for particles
def draw(self, canvas):
canvas.draw_circle(self.position, PARTICLE_RADIUS, 1, self.color, self.color)
# string method for particles
def __str__(self):
return "Particle with position = " + str(self.position) + " and color = " + self.color
# draw handler
def draw(canvas):
for p in particle_list:
p.move(random.choice(DIRECTION_LIST))
for p in particle_list:
p.draw(canvas)
# create frame and register draw handler
frame = simplegui.create_frame("Particle simulator", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
# create a list of particles
particle_list = []
for i in range(100):
p = Particle([WIDTH / 2, HEIGHT / 2], random.choice(COLOR_LIST))
particle_list.append(p)
# start frame
frame.start()
2 while loop and for loop
2.1 demo
def list_extend_many1(lists):
"""Returns a list that is the concatenation of all the lists in the given list-of-lists."""
result = []
for l in lists:
result.extend(l)
return result
def list_extend_many2(lists):
result = []
i = 0
while i < len(lists):
result.extend(lists[i])
i += 1
return result
def list_extend_many3(lists):
result = []
i = 0
while i < len(lists):
result += lists[i]
i += 1
return result
def list_extend_many4(lists):
result = []
while len(lists) > 0:
result.extend(lists.pop(0))
return result
def list_extend_many5(lists):
result = []
i = len(lists) # i=4
while i >= 0:
i -= 1
result.extend(lists[i])
return result
2.2
list: an ordered sequence
dictionary: key-value mappings
sets: unordered collection of data with no duplicate
3 sets例子
3.1 sets例子 http://www.codeskulptor.org/#examples-sets.py
ordered of the elements in sets is not guaranteed.
instructors = set(['Rixner', 'Warren', 'Greiner', 'Wong’]) //使用了set()函数来建立一组set,输入参数为一个list. 这里的list=['Rixner', 'Warren', 'Greiner', 'Wong’]
instructors = set([]) //使用了set()来建立一组set,参数为一个list,这里的list=NULL
3 spaceship project
3.1 animated sprites demo
http://www.codeskulptor.org/#examples-asteroid_animation.py