Thanks to ICPO/MRO, if a child Python class doesn’t define a method, the parent method will be invoked:
I just got back from PyCon US. It was delightful; I saw old friends, met new ones, gave a tutorial on decorators, and spoke at the education summit. I’m a PyCon US sponsor, which means that I also had a booth, giving out T-shirts, books, stickers, and flyers about the LernerPython platform. Of course, the…
Inheritance in Python changes the attribute lookup path, aka the “method resolution order,” or MRO: Child.__mro__ # (__main__.Child, object) Child.__mro__ # (__main__.Child, __main__.Parent, object)
Set one Python class to inherit from another by putting the parent in (): Child.__bases__ # who does Child inherit from?
Python uses attributes where other languages use different terms (and data structures): – Instance variable — attribute on an instance (self)– Class variable — attribute on a class– Method — callable (function) attribute on a class
Python methods are stored on a class, not an instance. Given x.m(), how does Python find it? The ICPO rule: – First, look for an attribute on the _i_nstance.– Not there? Look on the _c_lass.– Not here? Look on the _p_arent.– Not there? Look on _o_bject, the final parent.
By default, every Python class inherits from “object”. You can see this by checking the __bases__ attribute on a class: __bases__ is a tuple — hinting (correctly) that Python supports multiple inheritance.
Creating a Python class? You’re already using composition, the has-a relationship. How? When you assign to an attribute (e.g., self.name = name) in a Person class, you’re saying, “Person has-a name”. name could be a builtin str, or an instance of a custom PersonName class.
Writing object-oriented Python? Don’t confuse the two core relationships: – has-a (“composition”). One object contains another. A Person has-a name. A Car has-a color.– is-a (“inheritance”). One class is similar to an existing one. An Employee is-a Person. A Car is-a Vehicle.
Python’s ternary operator is convenient, but easy to abuse: ‘A’ if s>=90 else ‘B’ if s>=80 else ‘C’ if s>=70 else ‘F’ Just because you CAN, doesn’t mean you SHOULD! For 3+ conditions, use if-elif-else. Save the ternary for comprehensions, lambdas, and return statement.