百行代码入门Python - Chapter2

以下代码均采用Python 3.5.2编写。
建立一个名为HelloWorld.py的文件,当然名字无所谓,只要不是文字提及的其它文件名字即可,读懂以下代码方可轻松入门Python:

#Class
class Bird(object):
    feather= True
    reproduction="egg"
    def chirp(self, sound):
        print(sound)
    def set_color(self,color):
        self.color=color
        return color

summer = Bird()
summer.chirp("jijijiji")
print(summer.feather)
print(summer.set_color("yellow"))

#Magic Method
class Bird2(object):
    def __init__(self, sound):
        self.sound=sound
    def chirp(self):
        print(self.sound)

summer = Bird2("jiji")
summer.chirp()

#Inheritance
class Chicken(Bird):
    how_to_move = "walk"
    edible=True

class Swan(Bird2):
    how_to_move = "swim"
    edible=False
    def chirp(self):
        super().chirp()
        print("jijijiji")

summer = Chicken()
summer.chirp("ji")
bird=Bird2("ji")
bird.chirp()
summer = Swan("ji")
summer.chirp()

#class list
i = [1, 2, 3, 4, 9.0, "Good", -1, True, False, "Bye"]
print(i.count(4))
print(i.index(3))
i.append(6)
print(i)
i.reverse()
print(i)
i.pop()
print(i)
i.remove(2)
print(i)
i.insert(0,9)
print(i)
i.clear()
print(i)

#iter
example_iter=iter([1,2,3,4])
print(type(example_iter))
print(example_iter.__next__())
print(example_iter.__next__())
for i in example_iter:
    print(i, "example_iter in for")

#generator
def gen():
    a=100
    yield a
    a=a*8
    yield a
    yield 1000

print(type(gen()))
for i in gen():
    print(i)


#class Module
import time
print(dir(time))

from time import sleep
sleep(1)
print("Wake Up")

from time import *
sleep(1)
print("Wake Up 2")

time.sleep(1)
print("Wake Up 3")

为了方便起见,可以将未读到的章节注释掉。

上一篇:百行代码入门Python - Chapter 3


下一篇:一个简单的Python plot曲线图示例