定义类:如何从对象类继承(Defining a Class: How to inheriting from object class)

编程入门 行业动态 更新时间:2024-10-26 02:36:58
定义类:如何从对象类继承(Defining a Class: How to inheriting from object class)

所以这是我的代码,我试图让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

更多推荐

本文发布于:2023-08-05 22:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1441107.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:定义   对象   Defining   Class   object

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!