How does self work in python? [duplicate]

0

I would like to know how self works in python, I know that it has to do something with the classes but I do not have it so clear and I need to know to convert it into an arrangement, here there is little of the code

class Button(pygame.sprite.Sprite):
    def __init__(self,image):
       pygame.sprite.Sprite.__init__(self)
       self.image, self.rect = load_image(image)
    def setCords(self,x,y):
       self.rect.topleft = x,y
       screen.blit(self.image, (x,y))
    def pressed(self,mouse):
        if mouse[0] > self.rect.topleft[0]:
            if mouse[1] > self.rect.topleft[1]:
                if mouse[0] < self.rect.bottomright[0]:
                    if mouse[1] < self.rect.bottomright[1]:
                      return True
                    else: return False
                else: return False
            else: return False
         else: return False

The help is already appreciated and if you can give me advice on how to pass it to arrangement and function I would be very grateful to you because I am just with all this

    
asked by Wolf 07.10.2018 в 06:44
source

1 answer

0

self serves to refer to the class itself. That is, if we have for example a class 'foo' with the method get name and its constructor, it would be as follows:

class foo(object):
    name = ""

    def __init__(self, name="bar"):
        self.name = name

    def get_name(self):
        return self.name

In the previous code block you can see self in two different ways. When it is received by parameter in each of the methods, it means that this method is passed the object itself , in this case, an object of the class foo .

On the other hand, you have self within the implementation of each method. This refers to the attribute of the same class. When we define classes in Python it is necessary to pass by parameter self , because otherwise, we could not access the attributes or methods of the class.

I hope it helps you

    
answered by 08.10.2018 в 16:23