On ‘self’ in Python

usecase

The concern is documenting the keyword self as used in python — when working within the OOP (Python w/ classes)

1. intro: on instance method

  • Instance methods are methods that can be called on objects, i.e. unique instances of the class
  • INSTANCE means that with this method it is possible to ACCESS UNIQUE DATA of the instantiated object of that class

If you have two objects each created from a car class, then they each may have different properties. They may have different colors, engine sizes, seats, and so on.

https://www.makeuseof.com/tag/python-instance-static-class-methods/

  • belong to the family of methods together with
  • class methods (a method for the whole class)
  • static methods (a method for the whole runtime)

1.1. the four rules for method names (same for variables)

  1. all lower case
  2. words separated by an underscore
  3. non-public methods begin with a single underscore
  4. if a method name needs to be mangled, two underscores may begin the name

2. CODE

3. instance method requirement: self parameter

  • instance method must accept a reference to the instance of the class to which the method was called
  • this is the keyword self as the first argument
  • of course, self is just a convention as it is a parameter

4. import class from file

5. instantiate an object

6. shorthand method call: no self parameter

  • note that in this way of calling the method you are not passing the argument name for the self parameter
  • check the code
  • check the REPL and call the method without the reference to the class at all

7. longhand method call: argument for self parameter

  • the longhand format with the self passed would be
  • here you proceed ClassName.method_name(object_name) where object_name argument stands for self parameter

8. sources

Written by

today I learnt… | as a support eng of the wonderful Snowplow Analytics, expect everything around modern (postmodern?) business intelligence

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store