selfkeyword 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
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
selfkeyword and a
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