How Do You Use the Python self Keyword?

Problem scenario
You have seen Python functions defined using the self keyword. You want to test it out. How do you do this?

Solution
First of all, self is NOT a keyword in Python. Yes, you should probably use the word "self" when it is invoked. This is a well-accepted convention. It may be an unwritten rule. But you do not need to use the word "self".

The word "self" [in the context of Python object-oriented programming] allows you to refer to the instance of the object itself (according to this posting).

Here is an example where self is not used:

class Cartesian(object):
    def __init__(wwxxyyzz,a = 0,b = 0):
        wwxxyyzz.a = a
        wwxxyyzz.b = b

    def distance(wwxxyyzz):
        return (wwxxyyzz.a**2 + wwxxyyzz.b**2) ** 0.5 # Pythagorean theorem.

contint = Cartesian(4, 1)
print(contint.distance())

The above object instantiation and invocation of a function encapsulated within the object are all done with passing the "wwxxyyzz" variable. This is defined with the init constructor. You can replace "wwxxyyzz" with the word "self". When referring to the object itself outside of the class, use the object's name; we use "contint" in the above example. When referring to the object itself from within the class, use the word self.

Here is the same program but with the word "self":

class Cartesian(object):
    def __init__(self,a = 0,b = 0):
        self.a = a
        self.b = b

    def distance(self):
        return (self.a**2 + self.b**2) ** 0.5 # Pythagorean theorem.

contint = Cartesian(4, 1)
print(contint.distance())

Leave a comment

Your email address will not be published. Required fields are marked *