12.4 Self Keyword

Self Keyword

The self keyword is a reference to the current instance of the class, and it is used to access instance variables and more. Instance variables are variables unique to an instance created by the object. In other words, every instance of a class potentially has different instance variables. Similarly, instance methods are methods designed to modify instances. They can access the instance variables. In the example below, instances of the class Tesla can potentially have a different maxSpeed and color.
The reason why you need self as a parameter is to tell the Python interpreter that the method is an instance method.
Once an instance variable is created, it can be accessed anywhere in the class if you use the self keyword and a . before it
class Tesla: def __init__(self, maxSpeed=120, color="red"): self.maxSpeed = maxSpeed self.color = color def change(self, c): self.color = c p1 = Tesla(140, "blue") p1.change("yellow") print(p1.color) # prints "yellow" p1.color = "hello" print(p1.color) # prints "hello"
View code on GitHub.
You can actually access variables/attributes that aren't instance variables anywhere in the class if you put them outside of methods, as shown below
class example: your_attribute = True # can be any type def access_attr(self): print(self.your_attribute) self.your_attribute = False our_instance = example() example.access_attr() # would print True # would also change your_attribute to False

Previous Section

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.