笨方法学Python 习题 41: 物以类聚

来源:互联网 发布:vero moda除了淘宝 编辑:程序博客网 时间:2024/04/28 05:37

#!usr/bin/python# -*-coding:utf-8-*-class TheThing(object):    def __init__(self):        self.number = 0    def some_function(self):        print("I got called.")    def add_me_up(self, more):        self.number += more        return self.number# two different thingsa = TheThing()b = TheThing()a.some_function()b.some_function()print("_"*15)print(a.add_me_up(20))print("_"*15)print(b.add_me_up(30))print("_"*15)print(a.number)print("_"*15)print(b.number)# Study this. This is how you pass a variable# from one class to another. You will need this.class TheMultiplier(object):    def __init__(self, base):        self.base = base    def do_it(self, m):        return m * self.basex = TheMultiplier(a.number)print("_"*15)print(x.do_it(b.number))print("_*"*15)class Animal(object):    passclass Dog(Animal):    def __init__(self, name):        self.name = nameclass Cat(Animal):    def __init__(self, name):        self.name = nameclass Person(object):    def __init__(self, name):        self.name = name        self.pet = Noneclass Employee(Person):    def __init__(self, name, salary):        super(Employee, self).__init__(name)        self.salary = salaryclass Fish(object):    passclass Salmon(Fish):    passclass Halibut(Fish):    passrover = Dog("Rover")satan = Cat("Satan")mary = Person("Mary")mary.pet = satanfrank = Employee("Frank", 120000)frank.pet = roverflipper = Fish()crouse = Salmon()harry = Halibut()

运行结果如下:

加分习题

研究一下 __dict__ 是什么东西,应该怎样使用。

再为游戏添加一些房间,确认自己已经学会使用 class 。

创建一个新版本,里边使用两个 class,其中一个是 Map ,另一个是 Engine 。提示: 把 play 放到 Engine 里面。

常见问题回答

result = sentence[:] 是做什么的?

这是 Python 中复制 list 的方法。你用了列表切片(list slice)的语法 [:] ,其效果是将列表从头到尾每个元素切片出来并创建了一个新列表。

这脚本好难跑起来啊!

到现在为止你应该有能力写脚本并让脚本运行起来了。偶尔你会碰到点小困难,但其实也没什么复杂的。用你学过的各种技巧去克服困难吧。