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.
Want an if-else statement in your Python lambda? You can’t because it’s a statement. Instead, use the ternary operator: In other words: If it’s a string, return the value. If not, return it as a string.
In yesterday’s post, you saw Python’s ternary operator (an if-else expression). It’s useful in lambdas and comprehensions: VALUE_IF_TRUE if CONDITION else VALUE_IF_FALSE For example:
Defining a custom __format__ method in Python? Go bananas, if you want. For example (see image for full demo):
Defining __format__ in a Python class? Check if the second argument is ”, meaning no format code:
Want your Python class to take custom format codes? Define __format__. This method returns self.x *except* with a :< format. Then it reverses self.x:
A Python value x in an f-string’s {} normally interpolates str(x), aka x.__str__. Want the repr instead, aka x.__repr__? Put !r after the value: f'{x}’ # returns str(x)f'{x!s}’ # also returns str(x), but unneededf'{x!r}’ # returns the repr
Have a Python datetime, and want to print it? Use an f-string, and pass a strftime-style format: f'{now:%Y-%m-%d}’ # year-month-datef'{now:%Y-%m-%d %H:%M:%S}’ # year-month-date hour:min:sec # Easily integrate into user outputf’Today is {now:%Y-%m-%d}, you know!’
Have a Python number, and want commas before every 3 digits? Use , in an f-string: Floats, too: Combine , and .2f: