You can get a long way in Python using the built in scalar and collections types. For many problems the built in types, together with those available in the Python Standard Library, are completely sufficient. Sometimes though, they aren't quite what's required, and the ability to create custom types is where classes come in.
As we've seen, all objects in Python have a type, and when we report that type using the type()
built-in function the result is couched in terms of the class of that type:
>>> type(5) <class 'int'> >>> type("python") <class 'str'> >>> type([1, 2, 3]) <class 'list'> >>> type(x*x for x in [2, 4, 6]) <class 'generator'>
A class is used to define the structure and behaviour of one or more objects, each of which we refer to as an instance of the class. By and large, objects in Python have a fixed type from the time they are created – or instantiated – to the time they are destroyed...