Python and Object Programming AhAh moment

Metal Owl

Summary

Clarifying Python code containing the mysterious “dot notation” of object-oriented languages.  An object is a combination of data stored within a specific class. A class is a blue-print (or framework) that defines attributes (containing the data) and methods that act as functions onto the data contained within the object.
The “dot notation” makes the code very concise. For example fruit.upper()will convert the word(s) contained within fruitto all uppercase, upper()being the method predefined for an object of class string (str.)

One Course, 5 minutes

A few years ago I followed a course now on LinkedIn Leaning (back then it was Lynda.com) that offered an amazing insight into Python code that had me confused for a long time.

The course is called Programming foundations fundamentals 2011 with Simon Allardice as the instructor. (The course is now retired but still available to LinkedIn subscriber. Accessing the link may require a subscription. UW-personnel can access via NetID.)

Even though there were hints early in the course, the section on Object Oriented Programming was key to finally making sense of a lot of Python code that I encountered elsewhere. Even though the course used Javascript as the vehicle to explain and convey programming concepts, both langages are “object-oriented languages.” But what does “object-oriented” mean?

Object Oriented Programming

The final revelation was within the 5 minute video titled “Introduction to object-oriented languages” that was the first video in Section 12 of the course titled: “Introduction to Object Orientation.” I am still thankful for these 5 minutes and I find it unfortunate that beginner course don’t usually mention this concept or the “dot notation” to use it, while in fact “dot notation” might just appear in the example codes without any explanation.

In summary there are 2 main types of languages: “procedural” and “object-oriented” which are newer (circa late 80’s.)

The concept to understand is that “objects” are a combination of “data” and “class.” The class can be understood as a “blueprint” that pre-defines properties or methods. Just as the blueprint of a house pre-defines where each room will be, it’s measurements, length, height, its location, etc. The pre-defined methods within a class are akin to a function i.e. they can “make something happen.” Objects also contain inherent “attributes” that contain the data and represent the state of an object.

Languages like Python offer many existing classes, and users can define more if they want.

All of this is best understood by a simple example. We’ll use the class str (string) to illustrate the use of methods and how this comes about in the form of “dot notation” which is the very thing that had me confused.

The following simple Python session first defines a string object that will contain the word (string) “apple” in lower case. The command type  confirms that the class is of type strthat in turn offers the built-in methods of that class that are called by “dot notation” just like a function, using the object name (fruit) and the name of the method and open/close parentheses, just like functions.

The first method shown in capitalize which will convert the first letter to uppercase. The second, upper will convert the whole word as capital letters. Finally, the count method will evaluate the number of occurrences of the supplied parameter. Here we count that the letter p occurs twice within the word.

red-yellow apple

>>> fruit = "apple"
>>> type(fruit)
<class 'str'>
>>> fruit.capitalize()
'Apple'
>>> fruit.upper()
'APPLE'
>>> fruit.count('p')
2 

 

strawberries on straw

Another method will swap the case of each letter from upper to lower or vice versa. Using a different fruit:

>>> fruit2 =  "strawBERRY"
>>> fruit2.swapcase()
'STRAWberry'
>>> fruit2.casefold()
'strawberry'
>>> fruit2.lower()
'strawberry'

Thus the object contains the data (here it was either apple or strawBERRY) while the class (type) of the object confers specific, pre-defined methods that works like functions on the data within the object itself.

This “dot notation” thus is very useful, but one has to know where the methods come from, which was a mystery to me until I saw that 5 min video.

This was extremely enlightening to understand, finally, what the Python code with “dot notation” meant.

But, how do I know which methods are available within an object?

One solution is to list all of the attributes to the object with the dir command, which will give a long list that might be confusing, but may prove useful. In the case of the str format for our fruit object we would get the long list:

>>> dir(fruit)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

This may be confusing at first, but at least the most obvious methods such as upper or lower should be obvious to find.

Learn more

The above description and example is a crude description of what object-oriented programming and concepts entail. The following article: “object-oriented programming (OOP)” [Archived] (By Technical Writer and Editor Alexander S. Gillis, Sarah Lewis) will provide more in-depth understanding. (Includes a short 2min video summary.)


Credits: Top image: metal owl by Pixabay anaterate, over shiny glass light background by Wolferl.
Strawberries on straw, and apple, by Pixabay Fruchthandel magazin