Advanced Python

Problem: Where and why should one create an __init__.py file?

Solution: Inside a folder/directory that’s meant to be a Python package containing a bunch of Python modules with useful functions, etc. that other Python scripts would be importing from (not strictly necessary as Python \(3.3+\) but still conventional to include).

  1. It executes the first time any module from that package is imported, thus providing a convenient place to run setup code.
  2. Expose functions/classes in internal submodules within the package directly at the package level, simplifying user API.
  3. Defining what gets imported when using wildcard import *.

Problem: (based on this YouTube video) Write some basic Python code to demonstrate how the object-oriented programming (OOP) paradigm works. In particular, show how to create a class, how to initialize attributes of object instances of the class, how to define methods associated to object instances of the class, how child classes can inherit properties of parent classes, and how classes themselves (not just their object instances) can also have class attributes and class methods or static methods.

Solution:

OOP_Fundamentals

Problem: Explain the purpose of magic methods in OOP Python, and write some code to demonstrate their applications.

Solution: Basically if you want to emulate the behavior of a lot of Python’s built-in classes like being able to concatenate strings using + or getting the length of a list using len(), but with your own classes rather than Python’s built-in classes, then magic methods are the way to go. Another way to put it is that you want to have access to this power of being able to do “operator overload”, so e.g. + is able to mean different things for adding two integers vs. two strings, because in all cases the + is just syntactic sugar for an underlying __add__ magic method that’s defined separately for the int class and the string class.

magic_methods

For more magic methods, you can starting type the double underscore, and see what VS Code IDE suggests:

Problem: Write Python code to demonstrate some applications of decorators, generators and context managers.

Solution: A decorator (@) is basically a wrapper function \(w\) that itself takes in some function \(f\) and maps it to a “wrapped” version \(w(f)\) of \(f\) with greater functionality but without cluttering the logic of \(f\) itself. A generator (yield) is also a function which is a bit like a discrete-time Markov chain. A context manager (with) guarantees that a program will exit even if there were errors during its execution.

Decorators_Generators_Context_Managers
This entry was posted in Blog. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *