对象 = 属性(数据) + 方法(函数)
一、对象创建
1 class创建类
2 使用这个类来建立一个真正的对象,这个对象称为这个类的一个实例。
3 范例:
创建类:
- class Ball:
- def bounce(self):
- if self.direction == "down":
- self.direction = "up"
创建Ball类的实例:
ball = Ball()
给实例加上属性并调用其方法
- ball.direction = "down"
- print("ball direction = {}".format(ball.direction))
- ball.bounce()
- print("ball direction = {}".format(ball.direction))
4 范例扩展
增加颜色属性,增加大小属性,多次调用bounce方法
代码如下:
- class Ball:
- def bounce(self):
- if self.direction == "down":
- self.direction = "up"
- else:
- self.direction = "down"
-
-
- ball = Ball()
- ball.direction = "down"
- ball.color = "red"
- ball.size = "small"
- print("ball direction = {}".format(ball.direction))
- print("ball color = {}".format(ball.color))
- print("ball size = {}".format(ball.size))
- ball.bounce()
- print("after bounce.ball direction = {}".format(ball.direction))
- ball.bounce()
- print("after bounce.ball direction = {}".format(ball.direction))
- ball.bounce()
- print("after bounce.ball direction = {}".format(ball.direction))
- ball.bounce()
- print("after bounce.ball direction = {}".format(ball.direction))
二、初始化对象
1 direction,color,size这些内容在对象创建时不存在,是在对象创建完成后创建的。一般情况下我们不这样做,通常我们在创建对象时会将需要的属性都设置好,这称为初始化对象。
在类定义时,可以定义一个特定的方法,名为__init__(),每次类被实例化时,都会调用这个方法。
代码范例:
- class Ball:
- def __init__(self, direction, color, size): # 初始化
- self.direction = direction
- self.color = color
- self.size = size
-
- def bounce(self):
- if self.direction == "down":
- self.direction = "up"
- else:
- self.direction = "down"
-
-
- ball = Ball("down", "red", "small")
- print("ball direction = {}".format(ball.direction))
- print("ball color = {}".format(ball.color))
- print("ball size = {}".format(ball.size))
- ball.bounce()
- print("after bounce.ball direction = {}".format(ball.direction))
- ball.bounce()
- print("after bounce.ball direction = {}".format(ball.direction))
- ball.bounce()
- print("after bounce.ball direction = {}".format(ball.direction))
- ball.bounce()
- print("after bounce.ball direction = {}".format(ball.direction))
三、魔法函数
打印对象及结果
- print(ball)
-
-
- <__main__.Ball object at 0x0000024982D11FD0>
此时系统默认调用一个魔法函数
def __str__(self)
默认会打印对象的3个方面的内容
1 实例在哪里定义
2 类名(Ball)
3 实例的内存位置
我们希望对象打印的内容:这是一个什么颜色的球
- def __str__(self):
- return ("this is direction:{},{},{} ball".format(self.direction, self.color, self.size))
再来打印对象
- print(ball)
-
-
- this is direction:down,red,small ball
self是什么?即具体的实例对象