Due to some complex scheduling issues, I am posting here the material we would have covered in lab tomorrow. Please feel free to contact me for any questions (firstname.lastname@example.org). Enjoy!
Python Objects and Classes (cont’d!)
What is the self variable in Python?
The self variable represents the instance of the object itself. Unlike most object-oriented languages that pass the instance of an object as a hidden parameter to the methods defined on an object; Python does not. It must be explicitly declared. All methods in python, including some special methods like initializer, have self.
In other words, the self variable refers to the object which invokes the method. When you create new object the self parameter in the __init__ method is automatically set to reference the object you have just created.
More theory…do’s and don’ts of Self:
You use self when:
- Defining an instance method. It is passed automatically as the first parameter when you call a method on an instance, and it is the instance on which the method was called.
- Referencing a class or instance attribute from inside an instance method. Use it you want to call a method or access a name (variable) on the instance the method was called on, from inside that method.
You don’t use self when:
- You call an instance method normally. For example if you input [instance = MyClass()], you call [MyClass.my_method] as [instance.my_method(some_var)] not as [instance.my_method(self, some_var)].
- You reference a class attribute from outside an instance method but inside the class definition.
Let’s try an example!
First, we must create an object from class:
Here’s an example I created on Jupyter notebook. If you’d like, I can email you the notebook as lines are colour formatted and the spaces match up to the correct inputs (as you know, your code will be affected by the spacing).
# constructor or initializer
def __init__(self, name, money):
self.__name = name
self.__balance = money # __balance is private now, so it is only accessible inside the class
def deposit(self, money):
self.__balance += money
def withdraw(self, money):
if self.__balance > money :
self.__balance -= money
return “Insufficient funds”
b1 = BankAccount(‘tim’, 400)
Now, I’d like to show you if it’s possible to access __balance data field outside of the class.
AttributeError: ‘BankAccount’ object has no attribute ‘__balance’
As you can see, now __balance is not accessible outside the class.
What questions do you have at this point? Does this match up with the aforementioned theoretical concept of self/hidden self data? Would you like more practice?