简体   繁体   中英

Class variables resetting in python

Right now I am having a problem where a class' values are being reset I am not sure where. can anyone help? Here is the code

while True:
   #some code#
   Hub().paint(gameDisplay)

The Hub/paint function is shown below

def paint(self, screen):
    if self.gimseen == 0 and self.pressed == 0:
        screen.blit(image1, (self.x, self.y))
        self.pressed = (pygame.mouse.get_pressed()[0])
        if self.pressed == 1:
            self.gimseen += 1

in some code I call a function that i also use to get the value of self.pressed is there any other way I could do this besides adding a line above the while loop that states that hub = hub()?

The reason your variables are resetting, is because you create a brand new instance of the Hub() each time your while loop loops. This means that each time you call paint() , any state you had with the previous instance of Hub() is lost. Instead, you need to create one instance of the Hub() class outside of the while loop, and then call the method paint() inside of the loop on the one instance of Hub() :

# only create one instance of hub.
hub = Hub()
# create you loop.
while True:
    # call the method paint on the
    # the one instance of Hub(); hub.
    hub.paint()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM