Want to change the index of a Python Pandas series? Just assign to it:
By default, a Python Pandas series has a RangeIndex, like a string or list: Set an index like this:
Is a Python value of a particular type? It’s tempting to say: Far better to say: Why?– Works with subclasses– Second argument can be a tuple of possibilities
When should you use inheritance in Python? – An existing class mostly does what you want– Inheriting reduces your work — you only define differences– It’s an IS-A relationship, not just HAS-A– Otherwise: prefer composition. Remember: Inheritance is a tool, not a default.
What is a Python metaclass? – A subclass of type– Classes can be instances of a metaclass, rather than type– The metaclass’s __init__ sets attributes and methods Realistically, you should probably use a decorator instead of a metaclass. (But they’re fun to play with!)
A Python class is an instance of type. So type.__new__ and type.__init__ create the class and set attributes. Consider MyType, a subclass of type, setting some attributes in its __init__. MyType is a *metaclass*, used like this:
Every Python class inherits (directly or not) from object. object is a class. So type(object) is type, the class of all classes. But type is a class, and inherits from object! So yes: object is an instance of type. And type inherits from object. Also: type(type) is type!
When you define a class, Python checks it can get an unambiguous MRO. Children must always precede parents. This gives a TypeError when D is defined, because B (child of A) comes after A.
In Python, invoke super as: Where’s self? Or the MRO? – At compile time, Python adds a __class__ closure cell.– At runtime, super() grabs self from the calling frame — and walks type(self).__mro__ from __class__. No arguments needed (unlike Python 2)!
Some Python rules for inheritance: – Use super().x() to find the next class with a method “x”– “Next” is defined on the instance, aka type(self).__mro__– Every ancestor class should also use super().x()– This allows multiple parents’ x() methods to run