将类放入列表中。Python
我需要写一个类,这个类可以添加形状。
这是我需要做的类:
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 changeColour(self, newColour):
def totalArea(self):
return
形状类:
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)
还有一个正方形类。
我该怎么把颜色等信息,还有形状的类名放进一个列表里,以便后续使用呢?或者有什么更好的方法吗?
谢谢!
3 个回答
0
我觉得你不需要去创建Circle和Square的子类。试试这样做:
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
然后你可以像这样做一些事情:
d = Drawing()
d.addShape(Circle, c1, 0, 0, 5)
如果你想根据名字(也就是字符串)来查找颜色,这也是可以做到的,不过有几种不同的方法可以实现。
0
如果我理解你的问题没错的话,你可以直接把你的类的实例放到列表里:
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)]
1
我觉得你想要做的事情还不是很清楚,不过我可以给你一些建议:
- 你应该把你目前写的代码展示给我们看
- 如果这是作业的话,记得标明是作业
在Python中,你可以往列表里添加任何东西,所以试试看吧:
myList = [circle_instance, CircleClass, 'some-color', 1337]
注意,我可以在列表里放入我的形状实例、类、文本、整数,或者我想放的任何东西。