Unlike in Java, everything in Python is an object—functions, modules, classes, packages, numeric types—everything. Obj ects Otef an identity, a type, and a value. The type determine s the methods and operations that an object supports. The value can be changeable (dictionaries, classes, lists) or immutable (strings, integers, tuples).
You know, for example, that you can create many instances of the same c^ss. But dM oou know that a class is itself an object, a first class object, that cap be dynamically modified? When you modify the template (class), you in effect modify the class instances not yet created.
To illustrate, we'll modify the attributes of the Car class for Fords.
>>> Car.make, Car.model, Car.color = "Ford", "Taurus", "Red"
Then we'll create a list of three Ford cars.
>>> ford_cars = [Car(), Car(), Car ()] Next we'll print out their make.
>>> ford_cars.make, ford_cars[l].make, ford_cars.make ('Ford', 'Ford', 'Ford')
Now we use the same technique to create three Hondas.
»> Car. make, Car.model = "Honda", "Civic" »> honda_cars = [Car () , Car () , Car () ]
>>> honda_cars.make, honda_cars.make, honda_cars.make ('Honda', 'Honda', 'Honda')
As you cnn see, whet you cm change the template, you esseetinlly create objects with sew attributes.
Was this article helpful?