【问题标题】:Defining a class in python in python在python中定义一个类
【发布时间】:2012-04-16 01:40:51
【问题描述】:
class Rectangle(object):

def __init__(self, (top left corner), width, height):
    """
    __init__(self, (x, y), integer, integer)
    """

    self._x = x
    self._y = y
    self._width = width
    self._height = height

def get_bottom_right(self):
    x + self.width = d
    y + self.height = t

return '' + d,t

所以我想为一个矩形创建一个类,我想找到矩形的右下角。通过将高度和宽度添加到左上角可以找到矩形的右下角。例如。 (2,3),4,7 将使底角为 (6,10)。但是,我不相信我的代码是正确的。这是我第一次使用类,所以关于如何解释它的一些提示和技巧将非常有帮助。

【问题讨论】:

  • 当你发布代码时,你可以确保它的格式正确,因为它在 python 中很重要。
  • 抱歉,下次发帖时我会记住这一点。

标签: python class self


【解决方案1】:

我想你想要的是这个

class Rectangle(object):
  def __init__(self, top_corner, width, height):
    self._x = top_corner[0]
    self._y = top_corner[1]
    self._width = width
    self._height = height

  def get_bottom_right(self):
    d = self._x + self.width
    t = self._y + self.height
    return (d,t)

你可以这样使用

# Makes a rectangle at (2, 4) with width
# 6 and height 10
rect = new Rectangle((2, 4), 6, 10) 

# Returns (8, 14)
bottom_right = rect.get_bottom_right

另外,你可以通过创建 Point 类来节省一些时间

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

【讨论】:

  • 谢谢,这就是我想要的。我不知道如何用 x 和 y 定义 top_corner。
【解决方案2】:
class Rectangle(object):
  def __init__(self, pos, width, height):
    self._x = pos[0]
    self._y = pos[1]
    self._width = width
    self._height = height
  def get_bottom_right(self):
    d = self._x + self._width
    t = self._y + self._height
    return d,t

代码在这里运行:http://codepad.org/VfqMfXrt

【讨论】:

  • 我想找到矩形的底部。基本上我想添加左上角(这将是x,y)并将宽度添加到x并将高度添加到y。谢谢你的回复
猜你喜欢
  • 2012-01-02
  • 2010-12-02
  • 2014-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
  • 1970-01-01
相关资源
最近更新 更多