python-3.x 减少对同一类的调用次数

kq4fsx7k  于 2023-05-19  发布在  Python
关注(0)|答案(2)|浏览(102)

我有问题-我可以打电话给同一个班级9次吗?

self.level1 = LevelButton(10, 10, "1", "black", "lightgreen")
        self.level2 = LevelButton(50, 10, "1", "black", "lightgreen")
        self.level3 = LevelButton(100, 10, "1", "black", "lightgreen")
        self.level4 = LevelButton(150, 10, "1", "black", "lightgreen")
        self.level5 = LevelButton(200, 10, "1", "black", "lightgreen")
        self.level6 = LevelButton(250, 10, "1", "black", "lightgreen")
        self.level7 = LevelButton(300, 10, "1", "black", "lightgreen")
        self.level8 = LevelButton(350, 10, "1", "black", "lightgreen")
        self.level9 = LevelButton(400, 10, "1", "black", "lightgreen")

有一个类LevelButton:

class LevelButton:
    x_0 = 0
    y_0 = 0
    text = ""
    fg_color = (0, 0, 0)
    bg_color = (0, 0, 0)

    def __init__(self, x_0, y_0, text, fg_color, bg_color):
        self.x_0 = x_0
        self.y_0 = y_0
        self.text = text
        self.fg_color = fg_color
        self.bg_color = bg_color

我能把它减少到一两行代码吗?

fiei3ece

fiei3ece1#

您可以列出这些LevelButton对象。就像这样

levelButtonList = []
i0=10
i1=50
for i in range(1,10):
    if i==1:
        levelButtonList.append(LevelButton(i0,10, "1", "black", "lightgreen"))
    else:
        levelButtonList.append(LevelButton(i1,10, "1", "black", "lightgreen"))
        i1+=50

之后,您可以通过使用列表的索引单独访问它们。

ars1skjm

ars1skjm2#

你可以用这段代码:

for i in range(1, 10):
    _i = max(10, (i - 1)*50)
    value = LevelButton(_i, 10, "1", "black", "lightgreen")
    self.__setattr__(f"level{i}", value)

两个内衬:

for i in range(1, 10):
    self.__setattr__(f"level{i}", LevelButton(max(10, (i - 1)*50), 10, "1", "black", "lightgreen"))

相关问题