Python Open Lab Nov 28: Blog Style!

Hello all,
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 (data@library.columbia.edu). Enjoy!
Python Objects and Classes (cont’d!)
Self: 
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:

  1. 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.
  2. 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:

  1. 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)].
  2. 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:
Input:

1       p1 – Person(‘anna’)   # here we have created a new person object called p1
2       print(p1.whoami())
3       print(p1.name)

 

1      You are anna
2      anna
As discussed in lab, it is bad practice to give access to your data fields outside of the class itself. Let’s see how we can hide data fields: To hide data fields, first you have to define private data fields. In Python, this can be done by using two leading underscores (__). Moreover, a private method can also be defined using two leading underscores.

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).
 

Expected Output:

 
 
Now, I’d like to show you if it’s possible to access  __balance  data field outside of the class.
Input:

 
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?