
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
make_record(name, fields)returns a new class built withtype(...). It has a class attributefields(a tuple), an__init__(self, *values)that sets each field (raiseTypeErrorif the number of values is wrong), and a__repr__likeShip(name='Wren', crew=4).public_methods(obj)returns a sorted list of the names indir(obj)that don't start with_and are callable.param_names(func)returns the list offunc's parameter names.
make_record(name, fields)returns a new class built withtype(...). It has a class attributefields(a tuple), an__init__(self, *values)that sets each field (raiseTypeErrorif the number of values is wrong), and a__repr__likeShip(name='Wren', crew=4).public_methods(obj)returns a sorted list of the names indir(obj)that don't start with_and are callable.param_names(func)returns the list offunc's parameter names.
main.py Python sleeping
Press Run to try your code, then Check to test it.