Python

Instance, Class, and Static Methods

TL:DR Instance methods need a class instance and can access the instance through self. Class methods don’t need a class instance. They can’t accessthe instance (self) but they have access to the class itself via cls.

2022-12-16

Class vs Instance Variable

TL;DR Class variables are for data shared by all instances of a class. They belong to a class, not a specific instance and are shared among all instances of a class.

2022-12-16

Abstract Base Class (ABC)

TL;DR Abstract Base Classes (ABCs) ensure that derived classes implement particular methods from the base class at instantiation time Using Python’sabc module help avoid bugs and make class hierarchies easier to maintain.

2022-12-11

Object Cloning

TL;DR Making a shallow copy of an object won’t clone child objects. → The copy is not fully independent of the original. A deep copy of an object will recursively clone child objects.

2022-12-11

Define Your Own Exception Classes

TL;DR Defining your own exception types will state your code’s intent more clearly and make it easier to debug. Derive your custom exceptions from Python’s built-in Exception class or from more specific exception classes like ValueError or KeyError.

2022-12-04

String Conversion

TL;DR Control to-string conversion in your own classes using the __str__ and __repr__ “dunder” methods The result of __str__ should be readable. The result of __repr__ should be unambiguous. Always add a __repr__ to your classes.

2022-12-04

Object Comparison: == vs is

The == operator compares by checking for equality (the objects referred to by the variables are equal, i.e. have the same contents) The is operator comparies identities (whether two variables are in fact pointing to the same identical object) Example

2022-12-04

Function: Return `None`

Python adds an implicit return None statement to the end of any function. In other words, if a function doesn’t specify a return value, it returns None by default. This means you can replace return None statements with bare return statements or even leave them out completely and still get the same result.

2022-12-04

Lambda Function

The lambda keyword in Python provides a shortcut for declaring small anonymous functions. Lambda functions behave just like regular functions declared with the def keyword. Example: >>> add = lambda x, y: x + y >>> add(5, 3) 8 It is equivalent to declaring the same add function with the def keyword (which would be slightly moer verbose):

2022-12-03

Function: First Class Object

TL;DR Everything in Python is an object, including functions. You can assign them to variables store them in data structures pass or return them to and from ohter functions First-class functions allow you to abstract away and pass around behavior in your programs.

2022-12-03