Reputation: 59
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)
Upvotes: 2
Views: 162
Reputation: 17168
To inherit from object
(or any other class), just put the class to inherit from in parentheses after the class name where you're defining it.
class Rectangle(object):
pass #class stuff goes here.
As to your other question, the object
class is most basic class in Python. Generally speaking, all classes should inherit directly from object
, unless they inherit from something else.
However, it sounds like you're confused about what inheritance and classes actually are, which means you probably ought to go read up on object-oriented programming in general, and inheritance in particular.
Upvotes: 2
Reputation:
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
Upvotes: 4