与孩子一起学编程14章

这一章,开始学习对象

什么是对象,如何创建和使用对象。对象包括两个方面:属性和方法。

如果要建立一个球,球就是一个对象,他要有属性和方法。

ball.color
ball.size
ball.weight
上面这些就是关于球的描述,为属性

球的方法可能包括

ball.kick()
ball.throw()
ball.inflate()
这些都是可以对球做的操作。

从上面球的对象例子,可以看出,属性就是包含在对象中的变量,方法就是包含在对象中的函数。对象=属性+方法,所以,可以利用对象把一个东西的属性和方法收集在一起。

python创建对象包括两步。

第一步,建立一个对象的描述和蓝图,称为类(class)。

第二步,使用类来建立一个真正的对象,这个对象称为类的一个实例(instance)。

下面来看一个建立类和实例的例子,创建一个简单的ball类

class Ball:

    def bounce(self):
        if self.direction == "down":
            self.direction = "up"
这是一个球的类定义,其中只有一个方法bounce(),属性并不包含在类中,它属于各个实例,因为每个实例都可以有不同的属性。

下面对上面的代码补充,使用ball类

class Ball:

    def bounce(self):
        if self.direction == "down":
            self.direction = "up"

myBall = Ball()
myBall.direction = "down"
myBall.color = "red"
myBall.size = "small"

print "I just created a ball."
print "my ball is", myBall.size
print "my ball is", myBall.color
print "my ball's direction is", myBall.direction
print "Now I'm going to bounce the ball"
print
myBall.bounce()
print "Now the ball's direction is", myBall.direction
运行后结果
>>> 
I just created a ball.
my ball is small
my ball is red
my ball's direction is down
Now I'm going to bounce the ball

Now the ball's direction is up
>>> 
对象初始化,有一种特定的方法,名为__init__(),下面有代码示例
class Ball:
    def __init__(self, color, size, direction):
        self.color = color
        self.size = size
        self.direction = direction

    def bounce(self):
        if self.direction == "down":
            self.direction = "up"

myBall = Ball("red", "small", "down")
print "I just created a ball."
print "my ball is", myBall.size
print "my ball is", myBall.color
print "my ball's direction is", myBall.direction
print "Now I'm going to bounce the ball"
print
myBall.bounce()
print "Now the ball's direction is", myBall.direction
运行后得出的结果和前一个代码块是一样的,区别就是这个使用了__init__()方法。

在python中,下面这个就有点小意思了,看看这样

>>> print myBall
<__main__.Ball instance at 0x01223A08>
>>> 
这是怎么回事,我可不要这样,有一个方法__str__(),让他来返回你想要的东西。

特殊方法,__str__(),定义自己的__str__()

class Ball:
    def __init__(self, color, size, direction):
        self.color = color
        self.size = size
        self.direction = direction
        
    def __str__(self):
        msg = "Hi, I'm a " + self.size + " " + self.color + " ball!"
        return msg

myBall = Ball("red", "small", "down")
print myBall
运行后结果
>>> 
Hi, I'm a small red ball!
>>> 
说了这么多,写了这么多的代码,又没注意到,在类属性和方法定义中多次出现“self”,为什么要这样,自己google吧,呵呵

这个没有任何特殊的含义,是遵循一个约定。

对象最为重要的两个方面:多态(polymorphism)和继承(inheritance)。有一个例子来示例多态

class Triangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def getArea(self):
        area = self.width * self.height / 2.0
        return area

class Square:
    def __init__(self, size):
        self.size = size

    def getArea(self):
        area = self.size * self.size
        return area
Triangle类和Square类都有一个名为getArea()的方法,如果有两个实例
>>> myTriangle = Triangle(4, 5)
>>> mySquare = Square(7)
就可以使用getArea()方法来分别计算它们的面积
>>> myTriangle.getArea()
10.0
>>> mySquare.getArea()
49
>>> 
在不同的示例中,一个方法做的工作不同,这就是一个多态的例子。

另一个继承,更好理解了,字如其意,python中从其他类中继承属性和方法的类称为派生类(derived class)或子类(subclass)。

看下面这个例子

class GameObject:
    def __init__(self, name):
        self.name = name

    def pickUp(self, player):
        # put code here to add object
        # to the player's collection

class Coin(GameObject):
    def __init__(self, value):
        GameObject.__init__(self)
        self.Value = Value

    def spend(self, buyer, seller):
        # put code here to remove the coin
        # from the buyer's money and
        # add it to the seller's money
我们并没有在方法中加入任何实际代码,只有一些注释来解释这些方法要做什么,这是一种未雨绸缪的方法,这种编写比较复杂的程序时,通常就会采用这种做法来组织他们的想法,空函数或方法称为代码桩(code stub)。

如果向运行前面的例子,会得到一条错误信息,因为函数定义不能为空。

要建立一个代码桩,可以用python关键字pass,作为一个占位符,上面的代码重写如下

class GameObject:
    def __init__(self, name):
        self.name = name

    def pickUp(self, player):
        pass
        # put code here to add object
        # to the player's collection

class Coin(GameObject):
    def __init__(self, value):
        GameObject.__init__(self)
        self.Value = Value

    def spend(self, buyer, seller):
        pass
        # put code here to remove the coin
        # from the buyer's money and
        # add it to the seller's money
怎么样,就这么简单,对象就介绍到这儿,还有些例子,以后会慢慢加入。下面把我们前面一章写的热狗代码,用对象的思想重新诠释一遍
class HotDog:
    def __init__(self):
        self.cooked_level = 0
        self.cooked_string = "Raw"
        self.condiments = []

    def __str__(self):
        msg = "hot dog"
        if len(self.condiments) > 0:
            msg = msg + " with"
        for i in self.condiments:
            msg = msg + i + ", "
        msg = msg.strip(", ")
        msg = self.cooked_string + " " + msg + "."
        return msg

    def cook(self, time):
        self.cooked_level = self.cooked_level + time
        if self.cooked_level > 8:
            self.cooked_string = "Charcoal"
        elif self.cooked_level > 5:
            self.cooked_string = "Well-done"
        elif self.cooked_level > 3:
            self.cooked_string = "Medium"
        else:
            self.cooked_string = "Raw"

    def addCondiment(self, condiment):
        self.condiments.append(condiment)
        
myDog = HotDog()
print myDog
print "Cooking hot dog for 4 minutes..."
myDog.cook(4)
print myDog
print "Cooking hot dog for 3 more minutes..."
myDog.cook(3)
print myDog
print "What happens if I cook it for 10 more minutes?"
myDog.cook(10)
print myDog
print "Now, I'm going to add some stuff on my hot dog"
myDog.addCondiment("ketchup")
myDog.addCondiment("mustard")
print myDog


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值