我是靠谱客的博主 积极萝莉,最近开发中收集的这篇文章主要介绍python入门 类的继承和聚合(五),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述



继承

class Rocket:
    def __init__(self, name, distance):
        self.name = name
        self.distance = distance

    def launch(self):
        return "%s has reached %s" % (self.name, self.distance)


class MarsRover(Rocket): # inheriting from the base class
    def __init__(self, name, distance, maker):
        Rocket.__init__(self, name, distance)
        self.maker = maker

    def get_maker(self):
        return "%s Launched by %s" % (self.name, self.maker)


if __name__ == "__main__":
    x = Rocket("simple rocket", "till stratosphere")
    y = MarsRover("mars_rover", "till Mars", "ISRO")
    print(x.launch())
    print(y.launch())
    print(y.get_maker())
simple rocket has reached till stratosphere
mars_rover has reached till Mars
mars_rover Launched by ISRO

聚合

class MarsRoverComp():
    def __init__(self, name, distance, maker):
        self.rocket = Rocket(name, distance) # instantiating the base
        self.maker = maker

    def launch(self):
        self.rocket.launch()

    def get_maker(self):
        return "%s Launched by %s" % (self.rocket.name, self.maker)


if __name__ == "__main__":
    z = MarsRover("mars_rover2", "till Mars", "ISRO")
    print(z.launch())
    print(z.get_maker())
mars_rover_comp has reached till Mars
mars_rover_comp Launched by ISRO



转载于:https://www.cnblogs.com/wangjiale1024/p/10311399.html

最后

以上就是积极萝莉为你收集整理的python入门 类的继承和聚合(五)的全部内容,希望文章能够帮你解决python入门 类的继承和聚合(五)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(86)

评论列表共有 0 条评论

立即
投稿
返回
顶部