python中的对象

对象 = 属性(数据) + 方法(函数)

一、对象创建

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是什么?即具体的实例对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

永远的麦田

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值