百行代码入门Python - Chapter 3

以下代码采用Python3.5.2编写。
新建一个HelloWorld.py文件,当然文件名无所谓,只要不和下文中提及的文件重名即可,输入如下代码:

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

import second
second.sleep()

import second as t
t.sleep()

import my_dir.third as mydir
mydir.sleep()

#file
f=open("test.txt","w")
f.write("I like python\r\n")
f.write("I like python too")
f.close()
print(f.closed)
f=open("test.txt","r")
content=f.read(1)
print(content)
content=f.readline()
print(content)
content=f.readlines()
print(content)
f.close()

#context manager
with open("test.txt","w") as f:
    f.write("Hello Python!")

print(f.closed)

class Vow(object):
    def __init__(self, text):
        self.text=text

    def __enter__(self):
        self.text="I say: "+self.text
        return self
    def __exit__(self, exc_type, exc_value, traceback):
        self.text=self.text+"!"

with Vow("I'm fine") as myVow:
    print(myVow.text)

print(myVow.text)

#pickle
import pickle
summer = Bird()
with open("summer.pkl","wb") as f:
    pickle.dump(summer,f)

with open("summer.pkl","rb") as f:
    summer=pickle.load(f)

print(summer.feather)

#operator method
class SuperList(list):
    def __sub__(self,b):
        a=self[:]
        b=b[:]
        while len(b)>0:
            element_b=b.pop()
            if element_b in a:
                a.remove(element_b)
        return a

print(SuperList([1,2,3])-SuperList([3,4]))

example_dict = {"a":1,"b":2}
example_dict.__delitem__("a")
print(example_dict)

#__dict__
class Chicken(Bird):
    fly=False
    def __init__(self, age):
        self.age=age
    def chirp(self):
        print("ji")

summer=Chicken(2)
print("===> summer")
print(summer.__dict__)
print("===> Chicken")
print(Chicken.__dict__)
print("===> Bird")
print(Bird.__dict__)
summer.chirp()

autumn = Chicken(3)
autumn.feather=False
print(summer.feather)
print(autumn.feather)
print(autumn.__dict__)
print(Bird.__dict__)
Bird.feather=3
print(summer.feather)

新建一个名为second.py的文件,输入以下代码,注意与上述文件保留着同一个目录下:

def sleep():
    print("I am sleeping")

在主文件所在目录下新建一个目录,名为my_dir,然后在该新目录下新建两个文件,一个是__init__.py,该文件用来提示IDE这个目录为模块目录,可以是空文件;另一个是third.py,输入以下代码:

def sleep():
    print("I'm sleeping in third.py")

方便起见,可以注释掉主文件中不需要或者还没读到的代码,一步步学习。

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


下一篇:百行代码入门Python - Chapter2