While I do believe, I have a good grasp over pythonic concepts, I don’t want to mess up my interview and make sure that I do rather well. So, I am going through the textbook:
I just want to get a hang of bits of textbook definitions to make sure that I don’t speak garbage or don’t lose out on words.
What is ‘self’ in python?
Self refers to an instance of a class. It is used to access variables, attributes and methods of a class.
What is ‘__init__’ in python?
‘__init__’ is an instance method in a class used to initialise objects in python. It is a constructor basically.
What are special methods in Python?
The Python interpreter invokes special methods to perform basic object operations, often triggered by special syntax. The special method names are always written with leading and trailing double underscores. For example, the syntax
obj[key]is supported by the__getitem__special method. In order to evaluatemy_collection[key], the interpreter callsmy_collection.__getitem__(key).The first thing to know about special methods is that they are meant to be called by the Python interpreter, and not by you. You don’t write my_object.__len__(). You write len(my_object) and, if my_object is an instance of a user-defined class, then Python calls the __len__ method you implemented.
Why len () Is Not a Method ? [Copied from the book]
I asked this question to core developer Raymond Hettinger in 2013, and the key to his answer was a quote from “The Zen of Python”: “practicality beats purity.” In “How Special Methods Are Used”, I described how
len(x)runs very fast whenxis an instance of a built-in type. No method is called for the built-in objects of CPython: the length is simply read from a field in a C struct. Getting the number of items in a collection is a common operation and must work efficiently for such basic and diverse types asstr,list,memoryview, and so on.In other words,
lenis not called as a method because it gets special treatment as part of the Python Data Model, just likeabs. But thanks to the special method__len__, you can also makelenwork with your own custom objects. This is a fair compromise between the need for efficient built-in objects and the consistency of the language. Also from “The Zen of Python”: “Special cases aren’t special enough to break the rules.”
I think I had a good time reading the 1st chapter, and definitely enjoyed it.
I work on the unceded traditional Coast Salish lands including those of the Tsleil-Waututh (səl̓ilw̓ətaʔɬ), Kwikwetlem (kʷikʷəƛ̓əm), Squamish (Sḵwx̱wú7mesh Úxwumixw) and Musqueam (xʷməθkʷəy̓əm) Nations.


