【问题标题】:How do I run a function in a class for every object of that class?如何在一个类中为该类的每个对象运行一个函数?
【发布时间】:2019-10-18 07:11:26
【问题描述】:

正如标题所说,我想缩短这个:

while run:
        global mouse
        mouse = pygame.mouse.get_pos()

        first_button = button(pic, .1, .1, .1, .1)
        second_button = button(pic, .25, .1, .1, .1)
        third_button = button(pic, .75, .1, .1, .1)
        first_button.drawButton()
        second_button.drawButton()
        third_button.drawButton()

到这样的事情:

while run:
        global mouse
        mouse = pygame.mouse.get_pos()

        first_button = button(pic, .1, .1, .1, .1)
        second_button = button(pic, .25, .1, .1, .1)
        third_button = button(pic, .75, .1, .1, .1)
        button.drawButton()

但是当我这样做时,它会显示“drawButton() 缺少 1 个必需的位置参数:'self'”......作为参考,这是我的按钮类:

class button:
    global uiX, uiY, uiW, uiH
    def __init__(self, image, x, y, w, h):
        self.image = image
        self.bx = int(uiX + (x * uiW))
        self.by = int(uiY + (y * uiH))
        self.bw = int(w * uiW)
        self.bh = int(h * uiH)

    def drawButton(self):
        pic = pygame.transform.scale(self.image, (self.bw, self.bh))
        win.blit(pic, (self.bx, self.by))
        if ((self.bx < mouse[0] < (self.bx + self.bw)) and (self.by < mouse[1] < (self.by + self.bh))):
            pygame.draw.rect(win, (0, 0, 0,), (self.bx, self.by, self.bw, self.bh))

    def click(self):
        if ((self.bx < mouse[0] < (self.bx + self.bw)) and (self.by < mouse[1] < (self.by + self.bh))):
            print("Whatever the function will be")

【问题讨论】:

  • 您需要自己跟踪实例,可能使用listdict 之类的容器或任何您需要的容器
  • Rabbid76 已经给你答案了,也许你可以利用这个answer。它包含一个按钮类,该类利用了一些 pygame 功能,如 Rect、Sprite 和 Group。

标签: python class pygame


【解决方案1】:

那是错误的方式。一个类并不知道它的所有实例。

创建一个按钮列表(在主循环之前):

buttons = [
    button(pic, .1, .1, .1, .1)
    button(pic, .25, .1, .1, .1)
    button(pic, .75, .1, .1, .1)
]

for 循环中绘制按钮:

while run:
    global mouse
    mouse = pygame.mouse.get_pos()

    for b in buttons:
        b.drawButton()

【讨论】:

    【解决方案2】:

    您可以使用类方法来“注册”每个实例。 不知道这个推荐不推荐

    这是一个最小的例子:

    class Test:
        instances = []
    
        @classmethod
        def addInstance(cls, instance):
            cls.instances.append(instance)
    
        @classmethod
        def getInstances(cls):
            return cls.instances
    
        def __init__(self, arg):
            self.arg = arg
            self.__class__.instances.append(self)
    
    
    a = Test("Hello")
    b = Test("Hellu")
    c = Test("Helli")
    
    for instance in Test.getInstances():
        print(instance.arg)
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多