transport_identify()的问题

transport_identify()的问题

# -*- coding: utf-8 -*-
class Vehicle(object):
    # 自定义Vehicle类属性
    trans_type = 'SUV'
    speed = 0
    size = (0,)

    # 自定义实例的初始化方法
    def __init__(self, speed, size):
        self.speed = speed
        self.size = size

    # 自定义实例方法show_info,打印实例的速度和体积
    def show_info(self):
        print(f'Vehicle current type:{self.trans_type},speed:{self.speed}km/h,Volume:{self.size}')

    # 自定义实例方法move,打印“我已向前移动了50米”
    def move(self):
        print(f'I have moved forward 50 meters')

    # 自定义实例方法set_speed,设置对应的速度值
    def set_speed(self, new_speed):
        self.speed = new_speed

    # 自定义实例方法get_speed,打印当前的速度值
    def get_speed(self):
        print(f'The current speed is {self.speed} km/h')

    # 自定义实例方法speed_up,实现对实例的加速
    def speed_up(self):
        print(f'My speed has increased from {self.speed} to {self.speed + 10} km/h')
        self.speed += 10

    # 自定义实例方法speed_down,实现对实例的减速
    def speed_down(self):
        print(f'My speed has dropped from {self.speed} to {self.speed - 15} km/h')
        self.speed -= 15

    # 自定义实例方法transport_identify,实现对实例所属类型的判断
    def transport_identify(self):
        if self.trans_type == 'SUV':
            print('Type matched.')
        else:
            print('Type does not match')


if __name__ == "__main__":
    tool_1 = Vehicle(20, (3.6, 1.9, 1.75))

    # 调用实例方法 打印实例的速度和体积
    tool_1.show_info()
    # 调用实例方法 实现实例的前移
    tool_1.move()
    tool_1.set_speed(40)
    # 调用实例方法 打印当前速度
    tool_1.get_speed()
    # 调用实例方法 对实例进行加速
    tool_1.speed_up()
    # 调用实例方法 对实例进行减速
    tool_1.speed_down()
    # 调用实例方法 判断当前实例的类型
    tool_1.transport_identify()

transport_identify() 方法到底是要判断本类对象trans_type是否相同还是要判断对象是不是Vechile()类型对象?感觉题目描述没说清楚?

# 自定义实例方法transport_identify,实现对实例所属类型的判断
def transport_identify(self):
if isinstance(self, Vehicle):
print('Type matched.')
else:
print('Type does not match')


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
好帮手慕凡 2021-06-30 17:04:00

​同学,你好!transport_identify() 要实现对实例对象所属类型的判断。使用isinstance()方法判断实例对象tool_1是否所属Vehicle类。祝学习愉快!

  • 提问者 jjboy #1
    # 自定义实例方法transport_identify,实现对实例所属类型的判断
    def transport_identify(self):
    if isinstance(self, Vehicle):
    print('Type matched.')
    else:
    print('Type does not match')

    那么我写在最后的这个是对的吗?
    2021-06-30 17:55:15
  • 好帮手慕凡 回复 提问者 jjboy #2

    同学你好。有一出不对,if isinstance(self, Vehicle) : 判断语句。self本指的就是当前类的实例,肯定所属当前类。在这里可以接收一个示例对象进行比较。如下:http://img1.sycdn.imooc.com//climg/60dc43cc09b078ea07980484.jpg

    2021-06-30 18:15:05
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师