Shuttle类怎样在python3中生成

发布时间:2020-11-17 09:23:04 作者:小新
来源:亿速云 阅读:174

了解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类怎样在python3中生成大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. PHP中随机生成类的用法
  2. 怎么在Django中利用数据库表反向生成models类

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python python3 shuttle类

上一篇:python3中如何使用抽象类

下一篇:Python3中子类和父类的示例

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》