Code

Classes Are Objects

A class statement is really a call to type:

def hello(self):
    return f"I am {self.name}"

Ship = type("Ship", (), {"name": "Wren", "hello": hello})
# same as:
# class Ship:
#     name = "Wren"
#     def hello(self): ...
Ship().hello()    # 'I am Wren'

type(name, bases, namespace) builds a class from a name, a tuple of parent classes and a dict of attributes. So classes can be created at runtime, from data.

The flip side is introspection, examining objects while the program runs:

import inspect

dir(Ship())                  # every attribute name
getattr(Ship(), "hello")     # look one up by string
callable(Ship.hello)         # True
inspect.signature(hello)     # <Signature (self)>
list(inspect.signature(hello).parameters)   # ['self']

Assignment

  1. make_record(name, fields) returns a new class built with type(...). It has a class attribute fields (a tuple), an __init__(self, *values) that sets each field (raise TypeError if the number of values is wrong), and a __repr__ like Ship(name='Wren', crew=4).
  2. public_methods(obj) returns a sorted list of the names in dir(obj) that don't start with _ and are callable.
  3. param_names(func) returns the list of func's parameter names.