put a class in a list. python
i have to write a class which in that class can addShapes
heres the class I have to do
class Drawing(Circle, Square):
list = []
def addShape(self, theShape, colour, x, y, side):
self.list += [self.theShape(colour, x, y, side)]
def display(self):
return self.list
def move(self):
def 开发者_如何学PythonchangeColour(self, newColour):
def totalArea(self):
return
the shape classes:
class Shape(Point):
def __init__(self, colour, x, y):
Point.__init__(self, x, y)
self.colour = colour
self.centrePoint = (x,y)
def centre(self):
return self.centrePoint
def movePoint(self, newX, newY):
Point.move(self, newX, newY)
self.centrePoint = (self.x, self.y)
class Circle(Shape):
def __init__(self, colour, x, y, radius):
Shape.__init__(self, colour, x, y)
self.radius = radius
def getArea(self):
return math.pi * (self.radius * self.radius)
plus a square class.
how do you add colour etc. plus class name of the shape into a list so then it can be used. or whats the best way of doing this.
thanks
I don't think it's totally clear what you're trying to accomplish, but here's what I think:
- You should show us what you have written so far
- You should mark it as homework if it is homework
You can add anything to a list in Python, so just give it a shot:
myList = [circle_instance, CircleClass, 'some-color', 1337]
Note that I can have instances of my shapes, classes, text, integers, whatever I want in a list.
Provided I am understanding your question correctly, you can simply place instances of your classes into the list:
l = [Circle(BLACK, 0.0, 0.0, 12.0), Circle(GREEN, 10.0, 0.0, 3.0), Square(YELLOW, 5.0, 5.0, 1.0)]
I don't think you want to subclass Circle and Square. Try this:
class Drawing(object):
list = []
def addShape(self, theShape, colour, x, y, side):
self.list += [theShape(colour, x, y, side)]
def display(self):
return self.list
def move(self):
def changeColour(self, newColour):
def totalArea(self):
return
and then you can do something like this:
d = Drawing()
d.addShape(Circle, c1, 0, 0, 5)
If you're wanting to look up the colors based on the name (as a string), that would be doable, but there would be several different strategies.
精彩评论