簡體   English   中英

將 class 放入列表中。 python

[英]put a class in a list. python

我必須寫一個 class ,其中 class 可以添加形狀

這是我必須做的 class

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)

加上一個方形 class。

您如何將顏色等加上 class 形狀的名稱添加到列表中,以便可以使用它。 或者最好的方法是什么。

謝謝

我認為您要完成的工作並不完全清楚,但這是我的想法:

  1. 你應該向我們展示你到目前為止所寫的內容
  2. 如果是家庭作業,您應該將其標記為家庭作業
  3. 您可以將任何內容添加到 Python 的列表中,所以試一試:

    myList = [circle_instance, CircleClass, 'some-color', 1337]

請注意,我可以在列表中包含我想要的任何形狀、類、文本、整數的實例。

如果我正確理解您的問題,您可以簡單地將類的實例放入列表中:

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)]

我不認為你想繼承 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)

如果您想根據名稱(作為字符串)查找 colors,這是可行的,但會有幾種不同的策略。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM