[英]Defining a class in python in python
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)。 但是,我不相信我的代码是正确的。 这是我第一次使用类,因此一些有关如何解释这一点的提示和技巧将非常有帮助。
我想你想要的是
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.