最新公告
  • 欢迎您光临站盟网(原知事网),一个优质的网站源码基地、精品网站模板和插件。欢迎加入永久SVIP
  • Shuttle类如何在python3中生成?

    正文概述 知事网   2020-11-16 11:11   367

    之前提到过很多继承的内容,包括子类和父类其实也归属于这个问题。我们今天所要讲的Shuttle不完全用的是这一个类,还会涉及到继承另一个类的问题,这些话小编写在开头,以免给python初学者造成了不必要的误解。接下来就Shuttle类在python3中的生成操作,我们通过一个航天飞机的例子来讲解。

    如果你想模拟一个航天飞船,你可能要写一个新的类。但是航天飞机是火箭的一种特殊形式。你可以继承 Rocket 类,添加一些新的属性和方法,生成一个 Shuttle 类而不是新建一个类。

    航天飞船的一个重要特性是他可以重用。因此我们添加记录航天飞船服役的次数。其他基本和 Rocket 类相同。

    实现一个 Shuttle 类,如下所示:

    from math import sqrt
     
    class Rocket():
        # Rocket simulates a rocket ship for a game,
        #  or a physics simulation.
        
        def __init__(self, x=0, y=0):
            # Each rocket has an (x,y) position.
            self.x = x
            self.y = y
            
        def move_rocket(self, x_increment=0, y_increment=1):
            # Move the rocket according to the paremeters given.
            #  Default behavior is to move the rocket up one unit.
            self.x += x_increment
            self.y += y_increment
            
        def get_distance(self, other_rocket):
            # Calculates the distance from this rocket to another rocket,
            #  and returns that value.
            distance = sqrt((self.x-other_rocket.x)**2+(self.y-other_rocket.y)**2)
            return distance
        
    class Shuttle(Rocket):
        # Shuttle simulates a space shuttle, which is really
        #  just a reusable rocket.
        
        def __init__(self, x=0, y=0, flights_completed=0):
            super().__init__(x, y)
            self.flights_completed = flights_completed
            
    shuttle = Shuttle(10,0,3)
    print(shuttle)

    当一个子类要继承父类时,在定义子类的圆括号中填写父类的类名:

    class NewClass(ParentClass):

    新类的 __init__() 函数需要调用新类的 __init__() 函数。新类的 __init__() 函数接受的参数需要传递给父类的 __init__() 函数。由 super().__init__() 函数负责:

    class NewClass(ParentClass):
        
        def __init__(self, arguments_new_class, arguments_parent_class):
            super().__init__(arguments_parent_class)
            # Code for initializing an object of the new class.

    super()函数会自动将self参数传递给父类。你也可以通过用父类的名字实现,但是需要手动传递self参数。如下所示:

    class Shuttle(Rocket):
        # Shuttle simulates a space shuttle, which is really
        #  just a reusable rocket.
        
        def __init__(self, x=0, y=0, flights_completed=0):
            Rocket.__init__(self, x, y)
            self.flights_completed = flights_completed

    这样写看起来可读性更高,但是我们更倾向于用 super() 的语法。当你使用 super() 的时候,不必关心父类的名字,以后有改变时会变得更加灵活。而且随着继承的学习,以后可能会出现一个子类继承自多个父类的情况,使用 super() 语法就可以在一行内调用所有父类的 __init__() 方法。

    今天Shuttle的内容比较多,结合了科技类的航天飞机,两者都成了难以理解的内容了。小伙伴们不要灰心,多试几遍就可以了。

    转载自:python学习网 https://www.py.cn/


    站盟网 » Shuttle类如何在python3中生成?

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者
    请选择支付方式
    ×
    支付宝支付
    微信支付
    余额支付
    ×
    微信扫码支付 0 元