所以这是我的代码,我试图让Rectangle类从对象类继承。 我不明白对象类是什么意思,以及如何继承它。
class Rectangle: def __init__(self, coords, sizex, sizey): self._startx, self._starty = coords self._sizex = sizex self._sizey = sizey def getBottomright(self): '(%s, %s)' % (self._startx + self._sizex, self._starty + self._sizey) def move(self, pos): self._startx, self._starty = pos def resize(self, width, height): self._sizex = width self._sizey = height def __str__(self): return '((%s, %s), (%s, %s))' % (self._startx, self._starty, self._startx + self._sizex, self._starty + self._sizey) r = Rectangle((2, 3), 5, 6) print str(r) '((2, 3), (7, 9))' r.move((5, 5)) print str(r) '((5, 5), (10, 11))' r.resize(1,1) print str(r) '((5, 5), (6, 6))' r.getBottomright() (6, 6)So this is my code, i am trying to get the Rectangle class to inherit from the object class. I don't understand what does it mean by the object class, and how to inherit it.
class Rectangle: def __init__(self, coords, sizex, sizey): self._startx, self._starty = coords self._sizex = sizex self._sizey = sizey def getBottomright(self): '(%s, %s)' % (self._startx + self._sizex, self._starty + self._sizey) def move(self, pos): self._startx, self._starty = pos def resize(self, width, height): self._sizex = width self._sizey = height def __str__(self): return '((%s, %s), (%s, %s))' % (self._startx, self._starty, self._startx + self._sizex, self._starty + self._sizey) r = Rectangle((2, 3), 5, 6) print str(r) '((2, 3), (7, 9))' r.move((5, 5)) print str(r) '((5, 5), (10, 11))' r.resize(1,1) print str(r) '((5, 5), (6, 6))' r.getBottomright() (6, 6)最满意答案
要从object继承,只需将它放在类名后的括号中即可:
class Rectangle(object):基本上,继承的语法是这样的:
class ClassName(object1, object2, ...):在上面的代码中, ClassName继承自object1 , object2和您放置在其中的任何其他类(请注意,如果括号中有多个类,则称为“多重继承”)。
作为参考,这里是关于类,继承等的深入教程:
http://docs.python.org/2/tutorial/classes.html
To inherit from object, just put it in parenthesis after the class name:
class Rectangle(object):Basically, the syntax for inheritance is as so:
class ClassName(object1, object2, ...):In the above code, ClassName inherits from object1, object2, and any other classes you place in there (note that if there is more than one class in the parenthesis, it is called "multiple inheritance").
For reference, here is an in-depth tutorial about classes, inheritance, and the like:
http://docs.python.org/2/tutorial/classes.html
更多推荐
发布评论