accessing superclass methods from subclass
Jean-Michel Pichavant
jeanmichel at sequans.com
Mon May 10 07:14:47 EDT 2010
ben wrote:
> Ok, thanks for the info.
>
> What would be a better way to do this? What I'm trying to do is treat
> things in a reasonable OOP manner (all fairly new to me, esp. in
> Python). Here's a made-up example with a little more context. Let's
> say you're making a drawing program that can draw various shapes. So
> in the interest of not repeating oneself, I want a class Shape that
> handles everything that shapes have, such as a color, and a location.
> Then I can subclass Shape to create Square, which has code specific to
> drawing a square (e.g. 4 equal sides). So, like this:
>
> class Shape:
>
> x = 0
> y = 0
>
> def setColor(self,color):
> self.color = color
>
> def setLocation(self,x,y):
> self.x = x
> self.y = y
>
> def getLocation(self):
> return [self.x,self.y]
>
> class Square(Shape):
>
> size = 0
>
> def __init__(self,size):
> self.size = size
>
> def draw(self):
> location = getLocation()
> # code to draw shape from location[0],location[1] at size size
> # etc...
>
> It seems to me that you would want the location code handled in the
> Shape class so that I'm not rewriting it for Circle, Triangle, etc.,
> but I'm not allowed to call any of those methods from the subclass. I
> must be thinking of this in the wrong way. Help?
>
> thanks!
>
>
>
>
Hi Ben,
Please do not top post.
You already been given good advices, especially the one suggesting to go
through the tutorial. You're making basic mistakes here.
Here is a very simple version of your code.
class Shape:
def __init__(self, x=0, y=0):
self.x = 0
self.y = 0
self.color = None
def draw(self):
print 'drawing %s' % self
class Square(Shape):
def __init__(self,size):
self.size = size
def draw(self):
Shape.draw(self) # this is one way to call the base class method
location = (self.x, self.y)
# code to draw shape from self.x, self.y at size self.size
# etc...
mySquare = Square(5,2)
mySquare.color = 'red'
print mySquare.x
>>> 5
Since your attributes are flagged as public, you don't really need
setters & getters.
JM
More information about the Python-list
mailing list