ITeye博客

基础python代码

mcgtts · 2011-08-06 20:14 · Python · 编程语言 · Markdown

看完这段代码可以让我瞬间想起python的语法

 

# Open a file, read each line, and print it out
for line in open('file.txt'):
    print line

# Create a file and write to it
file = open("text.txt","w")
file.write("test line\n")
file.close()

# Create a small dictionary of names and ages and manipulate
family = {'Megan':13, 'Elise':8, 'Marc':6}
# result in 8
print family['Elise']

# Remove the key/value pair
del family['Elise']

# Create a list and a function that doubles its input. Map the 
# function to each of the elements of the list (creating a new list as a result)
arr = [1, 2, 3, 4, 5]
def double(x):return x*x
print map(double,arr)

# Create a class, inherit by another, and then instantiate it and invoke its methods
class Simple:
    def __init__(self, name):
        self.name = name;
    def hello(self):
        print self.name+"says hi."

class Simple2(Simple):
    def goodbye(self):
        print self.name+"says goodbye."

me = Simple2("Tim")
me.hello()
me.goodbye()

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。