【问题标题】:Classes: Interacting with 2 class instances in one function类:在一个函数中与 2 个类实例交互
【发布时间】:2018-03-23 17:52:49
【问题描述】:

这是我第一次在 python 中使用类,我很快编写了一个简单的类,可以让你按坐标移动火箭。我不知道如何制作一个名为“距离”的函数,它将返回两个不同实例(火箭)之间的距离。明确一点,我知道如何计算距离,我不知道如何构建函数

class Rocket:

    def __init__(self , start = (0, 0)):
        self.start = start
        self.x = self.start[0]
        self.y = self.start[1]
        if not self.crash():
            self.start = (0,0)
            print("You crashed!! Your position has been restarted to (0,0)")

    def __repr__(self):
        return "tbd"

    def get_position(self):
        return "Your curret posiiton is {}".format(self.start)


    def move_side(self,x):
        self.x += x
        self.start = (self.x, self.y)

    def move_up(self,y):
        self.y += y
        self.start = (self.x, self.y)
        if not self.crash():
            self.start = (0,0)
            print("You crashed!! Your position has been restarted to (0,0)")

    def move(self,x,y):
        self.x += x
        self.y += y
        self.start = (self.x,self.y)

    def land_rocket(self):
        self.y = 0
        self.start = (self.x,self.y)

    def crash(self):
        if self.y >= 0:
            return True
        return False

    def distance(self,other):
        return "???"

【问题讨论】:

  • 这里没有您尝试过的代码,应该包含在内。

标签: python python-3.x function class


【解决方案1】:

您需要定义一个带有额外参数的类方法,该参数是您要计算距离的对象。

要应用笛卡尔距离公式,请知道 ** 代表取幂,您可以导入 math.sqrt 代表平方根。

import math

class Rocket:

    ...

    def distance(self, other):
        return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2)

以上代码只要求otherxy属性,不需要是Rocket实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 2012-11-04
    相关资源
    最近更新 更多