Search code examples
pythonclassself

What exactly does self variable do? How do I use it in this case?


I've created a class called Colors() that has some lists defined in it. I have a method in it called set_alpha() that has to append the index 3 of the list with the parameter provided.

Here's the block of code:

class Colors():
    self.red = (255, 0, 0)
    self.blue = (0, 0, 255)
    self.green = (0, 255, 0)
    def set_alpha(self, alpha):
        self[3] = alpha

I knew this would be wrong before I even typed it because I do not understand the
self thing well. It gives an error saying self is not defined. What I want the result of my class is something like this -

When I do-

Colors.red.set_alpha(128)

I want red to become-

red = (255, 0, 0, 128)

Please explain EDIT: How do I solve my problem now? How do I use the method set_alpha() on a variable in the class?


Solution

  • The variable self represents the instance of a class object, here of class Colors. For example:

    c = Colors()
    c.a_method()
    

    When I call a_method() the variable self of the method will be c, considering a_method being defined as:

    def a_method(self):
        """A method that does something."""
        pass
    

    Now, in your case you would most probably want to have the red, green , blue and alpha attributes simply as integers, not as tuples:

    class Colors:
        def __init__(red, green, blue, alpha=255):
             self.red = red
             self.blue = blue
             self.green = green
             self.alpha = alpha
    
        def set_alpha(alpha):
             self.alpha = alpha
    

    Additionally, on class level the variable self is not defined so when you write self.red you will get an undefined error.