OBJECTIVES
- Learn simple principles for finding patterns in programs.
- Discuss how abstraction applies in the context of programming.
- Show built-in types available for use in your solution.
- Introduce classes as a means of creating your own types and abstractions.
- Examine an array of ready-made patterns.
FINDING PATTERNS IN PROGRAMS
Finding patterns during problem decomposition was first mentioned in Chapter 3 , in ‘Patterns and generalisation’.
It’s very important to look for patterns in a problem. During problem decomposition, when the problem is being broken down into a series of sub-problems, you’ll find concepts that share numerous similarities. These could be procedures that carry out near-identical work to each other. Or they could be entities that together form a single abstraction, a concept that allows you deal with them collectively by ignoring certain details.
This pattern-seeking work begins during early design work, but it doesn’t stop when a solution starts to be implemented as software. As you write the code, it continues to reveal further patterns you can take advantage of.
Each significant piece of functionality in a program should be implemented in just one place in the source code. Where similar functions are carried out by distinct pieces of code, it is generally beneficial to combine them into one by abstracting out the varying parts.
(Pierce, 2002)
This key piece of advice can be boiled down to two oft-quoted principles:
- Don’t repeat yourself.
- Find what varies and encapsulate it.
Let’s apply these in an example: the shape-drawing program discussed in earlier chapters. Chapter 3 pointed out that patterns among very similar, consecutive instructions can be replaced by a loop. The implementation of the shape-drawing solution in Chapter 9 stopped short of doing this, so let’s do it now.
For example, render_neutral_face looked like this:
This function calls draw_circle multiple times in a row. However, calls are not identical; the parameters vary. So, let’s follow the earlier advice.
First, don’t repeat yourself:
Then, find what varies and encapsulate it. The circle parameters vary, so we’ll capture those and encapsulate them in their own collection: 59
Recall that the solution draws several faces that differ by the shape of their mouths, so we can move the loop into its own reusable function.
The concepts behind abstraction were discussed in Chapter 4 .
ABSTRACTIONS IN PROGRAMMING
Finding patterns helps you to form abstractions. Recall that an abstraction is a means of expressing an idea in a certain context and one that suppresses some details deemed irrelevant in that context. Since Chapter 4 , we’ve seen numerous examples of abstractions. The first part of this book discussed them at a conceptual level. So far in Part II we’ve seen more concrete abstractions in programming. They might not have struck you as abstractions, but indeed they are.
Take something fundamental: a variable. When you see x = 42 , you can think of x conceptually as an integer variable. In reality, x refers to piece of computer memory, which includes all sorts of details you never need to worry about (its location in random access memory (RAM), the amount of memory it occupies, the maximum value it can store and so on). These details are hidden by the abstraction that is a Python variable.
Most other programming constructs we’ve covered are abstractions too: list comprehensions, loops, conditionals. The details of how they actually work ‘under the bonnet’ can be quite complex, but the creators of Python have made using them relatively simple by hiding those details (see the box below). After reading Chapter 9 , you’ll probably appreciate that functions and modules are abstractions too. That goes for anything that organises blocks of code into single units and hides the details within.
For an example of the extent to which a typical Python abstraction hides detail, consider something like creating a new list. To you, it’s as simple as doing my_list = [] , but Python is doing a lot of work behind the scenes. The procedure for creating a new list requires dozens of lines of code in C, the language used to implement Python ( Python.org , 2016).
In fact, a programming language is itself an abstraction. The computer doesn’t actually understand the code you type. Instead, your code gets transformed into machine language (a string of ones and zeroes) before the computer executes it. This means programming doesn’t involve writing out a tedious amount of binary digits but lets you focus on writing your solution instead.
While all this is important to know, this chapter focuses on another type of abstraction: the custom ones that you will be building as part of your solution. It discusses how you can best create your own abstractions using Python, as well as how to apply certain ready-made patterns to your own solution.
BUILT-IN TYPES
As part of a solution’s work, it will need to store various pieces of information. Some of the time, the nature of that information will line up with certain data types built into your programming language. For example, when you want to store a number, you’ll use an integer variable; when you want to store a piece of text, you can use a string.
Certain types of information are used in programs so often that every useful programming language provides them out of the box. Python is no exception (see Table 10.1 ).
Table 10.1 List of some of the most commonly used types in Python
Type | Example | Comments |
int | answer = 42 | Integer. Stores whole numbers. |
float | half = 0.5 | Floating point numbers. In other words, it stores real numbers (see the box below). |
bool | is_ready = True | Stores Boolean values, i.e. True or False. |
list | ages = [32, 31, 27, 31, 39] | Traditionally (though not necessarily) used as a variable-sized sequence of data where all the items have the same type. |
tuple | profile = (‘Palin’, 1943, ‘Sheffield’) | Traditionally (though not necessarily) used as a fixed-sized sequence of data where the items have mixed types. |
set | evens = {2, 4, 6, 8} | An unordered collection of items. No item can appear more than once in a set. |
dict | num_chapters = {‘bible’: 929, ‘hobbit’: 19} | Dictionary. Stores a collection of items (similarly to a list), but gives each item a unique, meaningful identifier to facilitate later retrieval. |
str | name = ‘Spock’ | String. Holds a piece of text. |
Exercise caution with the float type. Real numbers are theoretically capable of going on infinitely (like ⅓ being 0.33333…), but computers have limited space to store numbers. This means that some decimal calculations will be imprecise in surprising ways (for example, try evaluating 1.1 + 2.2 in Python and see what happens).
See this page for more details: https://docs.python.org/3/tutorial/
floatingpoint.html
To avoid these kinds of troubles, consider the decimal type, https://docs.python.org/3/library/decimal.html , which behaves more like the arithmetic you learn at school.
As well as storing data, these in-built types provide many of their own functions for manipulating their contents. For example:
capulets = [‘Juliet’, ‘Tybalt’, ‘Nurse’] # list
capulets.append(‘Rosaline’) # Adds a new item
pi = 3.142 # float
pi.is_integer() # Evaluates to False
sentence = ‘It was the best of times, it was the worst of times’
sentence.split(‘ ‘) # Evaluates to: [‘It’, ‘was’, ‘the’, # ‘best’, ‘of’, ‘times,’, ‘it’, ‘was’, ‘the’, ‘worst’, ‘of’, ‘times’]
Such functions represent very commonly used operations. Taking advantage of them helps to reduce the amount of work you have to do, so spend some time getting to know the functions available (see the Python language online reference: https://docs.python.org/3/library/stdtypes.html ). Reusing them means you don’t have to do the work yourself, plus they’re heavily tried, tested and optimised.
CREATING YOUR OWN TYPES
The car rental example was introduced in Chapter 4 ; see the section ‘Context and layers’.
Sometimes, a structure will emerge from your solution that no built-in type can satisfy. For example, in the vehicle rental scenario of Chapter 4 , several patterns emerged, including ‘car’, ‘van’ and ‘motorcycle’. Furthermore, these were all versions of the more general concept ‘vehicle’. Each type turned out to support particular properties (such as fuel amount, capacity) and operations (for example, check in, report mileage).
Python provides no vehicular types to help you here. In a case like this, when no built-in types meet your requirements, you can create your own. In Python, that means getting familiar with object-oriented programming (OOP), a subject with a wealth of material behind it. Covering all of OOP, even briefly, is out of scope for this book. Instead, we’ll examine only the material of immediate relevance to the creation of abstractions in Python. To illustrate this process, we’ll use the car rental scenario.
Whether built-in or not, a type is like a blueprint or template. An object is an instance of a type, put together from this blueprint. As such, there’s only one definitive blueprint for each type, but you can manufacture as many objects from it as you like. When you want to create your own type, you must write a ‘blueprint’ that tells the computer how to create objects of your custom type.
First steps
In Python, types are called classes. The starting point to creating a new type in Python is to define a new class:
The pass keyword in Python effectively says ‘I’m purposefully leaving the definition of this thing empty.’ It’s useful when you want to lay out the structure of a program but need to defer adding details.
Those two lines alone create a new class. You can prove it by entering these lines below:
x = Car()
print(type(x)) # Prints: <class ‘Car’>
The line x = Car() creates a new object of the Car class (that is, instantiates a Car object). Creating a new object this way is something you can do with any type, even the built-in ones:
my_integer = int() # Equivalent to my_integer = 0
print(my_integer) # Prints 0
print (type(my_integer)) # Prints <class ‘int’>
my_list = list() # Equivalent to my_list = []
print(my_list) # Prints []
print(type(my_list)) # Prints <class ‘list’>
Admittedly, Car is pretty useless as written. It can’t store relevant information and it has no operations to manipulate data. 60 Before it can become useful, we must flesh out its definition. Now we can start to build the abstractions we discovered when planning the vehicle rental scenario.
When you build abstractions, remember that you’re operating in a certain context that tells you at what level to operate. For example, a vehicle can be understood at different levels of detail. Someone modelling highway traffic can treat a vehicle as a single object, whereas someone working with car safety has to consider a car as made up of many components, each with their own behaviours.
For each abstraction, you will have identified:
- properties that belong to each abstraction;
- operations that can be applied to each abstraction.
These correspond with two things that classes in Python provide:
- data attributes : variables that belong to a particular object.
- methods : functions that belong to a particular object.
Let’s add an attribute to our class – the regulatory vehicle category that identifies this type of car (that is, ‘B’) : 61
category has now become an attribute of every Car object we will create. This makes it a class variable , because the value is the same for each instance of this class:
fiat = Car() # Creates a new instance of the Car class
ford = Car() # Creates another new instance of the Car class
print(fiat.category) # Prints ‘B’
print(ford.category) # Prints ‘B’
Some attributes vary among different instances of the same class. Every car may be category B by definition, but each car has its own model name. Python treats such attributes ( instance variables ) a little differently:
Some remarks about this:
- We’ve added a new, oddly named method to the Car class: __init__ . This is a special method called an initialiser , which is automatically executed whenever a new instance of a class is created. Its purpose is to provide a place for the programmer to add instructions that every object must execute when first created. It’s often used to specify the initial values of an object’s attributes.
- The __init__ method name begins and ends with a pair of underscores. This is a convention applied to all the special methods that objects can have (see the box below).
-
An __init__ method always has at least one parameter. By convention it is named self . You don’t pass this parameter yourself – it just magically appears and is always the first parameter.
- self represents the object itself. It’s a way of allowing an object to be introspective and able to manipulate its own properties.
- In addition to the self parameter, an initialiser may have an arbitrary number of additional parameters following it.
A Python special method can be called using a specific syntax rather than by calling the method. For example, __init__ is a special method because you don’t instantiate, say, a car by calling Car.__init__() , rather you just call Car() and that in turn calls __init__() .
Now, we can create objects with initial values and access those attributes later:
Let’s add another attribute of cars that’s very important to a rental agency: the mileage. We’ll have each car record its own mileage and also provide an operation to update it.
As with the model, the mileage is an instance variable of the Car class. The other addition is the update_mileage method. Some remarks on that:
- We could have just written my_car.mileage = 123789 , but since the process is more complicated than that (we first have to check that the odometer hasn’t been tampered with), we put the whole updating procedure into a class method and call that instead. By putting it in one place, this allows us follow the advice from earlier (that is, ‘don’t repeat yourself’).
- Once again, the self parameter appears. It has to be included because the method works with instance variables and so needs access to the particular object being dealt with (remember, many Car objects might exist and updating a car’s mileage applies only to one of them at a time). Again, it is passed automatically. Essentially, the value of my_car gets assigned to self without you needing to do anything.
Inheritance
Let’s take our example further by adding the other classes in the vehicle rental system: van and motorcycle.
You should see a problem similar to one observed in Chapter 9 . The process for updating the mileage is exactly the same for cars, vans and motorcycles, so we have repetitions of the same code. However, object-oriented programming provides ways to deal with this.
Cars, vans and motorcycles are all types of vehicle . So, what we’re really saying is that we follow the same process to update the mileage of every vehicle. OOP allows us to model this relationship using inheritance . When one class inherits from a parent class, it gains access to all the attributes and methods of the parent.
In terms of our example, we can say that Car , Van and Motorcycle are all subclasses of Vehicle . In other words: Car , Van and Motorcycle inherit from Vehicle . The subclasses take all the attributes and methods of Vehicle without you having to add them to each class explicitly:
The contents of the Car, Van and Motorcycle classes have (where identical) been moved into the Vehicle class, but they’re still implicitly in those subclasses because the subclasses inherit them from Vehicle . That means you can still execute the update_mileage method for a Car , Van or Motorcycle .
The only place those classes differed was their categories. Since this property varies among the subclasses, it needs to be specified in each subclass:
car = Car(‘Aston Martin DB5’, 32890)
van = Van(‘Ford Transit’, 67232)
motorcycle = Motorcycle(‘Triumph 900’, 3221)
print(car.category) # Prints ‘B’
print(van.category) # Prints ‘C’
print(motorcycle.category) # Prints ‘A’
Chapter 4 , section ‘Putting abstractions to use’ first mentioned the instantiation of abstractions.
Chapter 4 raised the problem of instantiating an abstraction. It may provide many conveniences but if it’s missing certain details, can it actually be made to work? Some details are necessary before you can instantiate an abstraction and put it to concrete use.
The last example instantiated not vehicles but specific types of vehicle. Instantiating a more abstract class might or might not be a valid thing to do – it depends on the context of your problem. Let’s say an exciting new vehicle comes along that’s like nothing else in the firm’s inventory. It’s certainly a vehicle, but it’s not a car, a van, nor or a motorcycle. So, should we just instantiate it as a Vehicle ?
c5 = Vehicle(‘Sinclair C5’, 10)
c5.update_mileage(20) # Works fine
So far, no problem. But what about when you try to access the vehicle’s category?
print(c5.category) # Error: ‘Vehicle’ object has no attribute ‘category’
Because the Vehicle class has no attribute called ‘category’, objects of that type have no such attribute. There are ways around this problem, ranging from simple to advanced:
- Add the category attribute to Vehicle . Give it a default value, like <undefined> .
- Create a new subclass for this new type of vehicle.
- Advanced: use a @property decorator to control access to category . Add a method to Vehicle like this:
@property
def category(self): raise NotImplementedError
For more information see: https://docs.python.org/3/library/functions.
html#property .
Polymorphism
A feature request for the vehicle rental system asks that a new function be added for printing out the model names of all vehicles in a list. It’s our job to write it.
Our new function could look something like this:
In this example, the function is given a list of objects named vehicles . All it knows 62 is that the list contains a collection of vehicles, but not which specific types of vehicles. Fortunately, it doesn’t need to know in order to do its job. This is possible because of polymorphism , a fancy term that describes the ability to deal with different types of objects using the same interface.
The Vehicle class provides an interface (that is, its attributes and methods) through which to manipulate any type of vehicle. Thanks to inheritance, we know that whatever attributes and methods the Vehicle class has, every subclass shares them. That means we can manipulate classes without knowing their exact type. We only require that all those classes support the expected interface. As a result, our code can be more concise and flexible.
It doesn’t matter that the underlying implementations might differ. For example, when a customer returns a vehicle, it must be found a parking bay. However, the method for finding a bay differs for each type of vehicle (vehicles are grouped into different parking sections by type).
Just like in the previous example, you can take a list of incoming vehicles of indeterminate type and make them each find an available parking bay in their respective section:
Polymorphism has its limits. If a subclass has its own attribute that the parent class doesn’t, then you can’t access it via the parent class. For example, vans have a payload, which cars and motorcycles don’t, so the Vehicle class can’t therefore have payload as an attribute. Therefore, we have to treat this attribute a little differently when initialising a Van , which means a Van has to have a different initialiser.
By giving the Van its own initialiser, we’re replacing the initialiser inherited from the Vehicle .
Initialising the common attributes (model and mileage) can still be done in the Vehicle class. We can just pass those to the initialiser of the parent class (aka the superclass, hence why it’s accessed via a method called super ). Then, we can initialise any attributes that belong solely to the Van .
Even when classes have their own particular methods and attributes, we can still take a polymorphic approach. If we have a list of vehicles and want to access payload information (which some vehicles don’t have), we can use Python’s built-in hasattr method, which tells us whether or not an object has a specific attribute or method:
In this example, the print statement is only executed if an object has a payload attribute.
Object composition
Let’s look closer at the parking bay feature, because it reveals an alternative way to structure related types that work together. A parking section is a type. It’s made up of several parking bays, which are another type. The question is: how can that relationship be modelled in a program?
Using inheritance to relate a vehicle and its subtypes made sense because a car (or a van or a motorcycle) is a particular type of vehicle. This can’t be said in the case of parking. A parking bay is not a type of parking section, nor vice versa. Instead, a parking section is made up of several parking bays.
When objects share this ‘ has a ’ relationship, you can implement this in a Python program by using object composition. Instead of one class inheriting another, one class is composed of others, like so:
Inheritance and composition are both often referred to as ‘ is a ’ and ‘ has a ’ relationships respectively. For example, a car is a vehicle, whereas a parking section has a parking bay.
Composition and inheritance solve similar problems, but among programming professionals there is often a preference for composition over inheritance. One reason for this is that composition proves to be more flexible than inheritance because it’s often easier to compose classes together than to try and put them into some kind of family tree structure. Nevertheless, inheritance is helpful when a family of classes do happen to fit such a structure.
READY-MADE PATTERNS
We’ve seen already how to spot patterns in your solution. We’ve also seen how to work those patterns and turn them into your own generalisations.
As you gain more experience in writing programs, you’ll notice that some patterns crop up repeatedly. Some details may differ a little in each case (for example, the variable names will differ), but some underlying structure is always the same.
Many useful patterns have already been found and catalogued over the years, lots of them described in books and websites. Becoming familiar with these patterns and applying them in your own solutions brings several key advantages:
- they’re tried and tested solutions to common problems.
- they reduce the amount of effort you have to put into your programs.
- being named, they provide a common ‘vocabulary’ for understanding the ideas in a solution.
- they hide certain details, enabling you to discuss solutions at a higher level. Instead of talking in terms of individual lines of code, you can refer to whole sections of a program using just one or two words.
Patterns range from very simple (realisable in just a few lines of code) to more complicated ones involving several objects acting in concert.
Simple patterns
In a sense, some of the built-in constructs of Python are simple patterns, for example building a list using a comprehension:
or prematurely exiting from a loop:
These are goals that Python’s authors thought were so useful and so common, they decided to build features into Python to support them.
Patterns have some dependence on programming language. A language might support a pattern directly, and others not. Some patterns might not even make sense in a particular language.
Some other simple patterns don’t have direct language support in Python and you must implement them completely yourself. Perhaps the simplest example is the temporary variable swap . It’s often the case in a solution that two objects need to swap their values with each other. This is a need that occurs so often, it has a standard solution:
my_ticket_number = 133
your_ticket_number = 4
temp = your_ticket_number
your_ticket_number = my_ticket_number
my_ticket_number = temp
print(‘Customer number 4 please!’)
This can be considered a pattern. The names and types of the variables may differ from case to case, but the underlying pattern is always the same.
Another simple pattern is lazy initialisation . Sometimes, it makes more sense to delay initialising an object’s attribute, but at the same time you might want to make sure that the attribute has a value when needed. Lazy initialisation combines the checking of an attribute’s value with the returning of it.
Lots of small patterns like these exist, but they’re often harder to spot than the built-in patterns. Despite this, you’ll build up familiarity by researching them and, more importantly, getting some practical experience.
Design patterns
Among programming professionals, talk of patterns in software has recently been dominated by object-oriented design patterns. Consequently, a web search for ‘software patterns’ will almost invariably bring up design patterns.
A design pattern typically involves several collaborating classes. Each pattern has a name and a reference to a specific design problem it solves. While they don’t directly correspond to executable code (you can’t just instantiate a design pattern), they have an archetypal structure that you can adapt and apply in your own situations.
Let’s illustrate this with a simple example: the facade pattern. Like an architectural facade, this pattern solves the problem of covering up some complexity by hiding it behind a simpler layer. Specifically, it conceals a complicated interface – probably involving several different classes – behind a simpler, unified interface.
In the following partial program, several objects model the ignition system of a car, which involves a complex chain of events among several components:
The ignition switch causes the battery to draw power to the coil, which transforms the power and sends it to the distributor cap, which causes the rotor to spin and trigger sparks in a series of spark plugs.
To make the process simpler, you can hide all the complexity behind a new facade class, in this case IgnitionSystem :
The IgnitionSystem wraps all those components together. As a result, it can behave more like a real ignition system. After all, a real car is not activated by manually carrying out each step – you simply turn a key. This facade provides a start_car method, the programmatic equivalent of turning the key.
The facade is an example of a structural pattern, in that the problem it addresses concerns how various objects interact with each other. Design patterns normally come in one of three flavours: creational, behavioural and structural. Let’s look at examples from those other two categories.
Creational patterns: suitable ways to create objects in different circumstances.
Behavioural patterns: common communication patterns and assignment of responsibilities among objects.
Structural patterns: simple ways to design relationships between objects.
In the current IgnitionSystem , the act of creating each object is very simple: a parameterless initialiser is called. However, creating objects in real solutions often gets complicated because they can be initialised in different ways depending on the circumstances. For example, batteries vary by how many amps they output; spark plugs depend on the size of the engine’s spark plug gap and so on. So, if you want your ignition system to be a standardised part able to work with different engines, 63 it’s going to have to work out what types of parts are in the engine and react accordingly. This means extra instructions will need adding to each instantiation. You could add them to the IgnitionSystem ’s initialiser, but it would become a very large and unwieldy method.
The factory pattern can help out here. It’s a creational pattern that helps when the act of creating a new object is complicated. The solution is to add a new class that encapsulates the instantiation process. An object no longer composes its own objects. Instead, it asks a factory to make them on its behalf.
So, instead of the IgnitionSystem making all those decisions, it entrusts them to a factory:
And so the initialiser of the IgnitionSystem looks like this:
Notice how we can use multiple patterns together. After adding a factory pattern, the existing facade pattern is still in place.
Finally, let’s examine a behavioural pattern: method chaining . When a process carries multiple steps, it can sometimes involve the creation of many objects. These have to be stored as local variables or instance attributes (as is the case with the IgnitionSwitch ). Method chaining removes the need for the storing of so many objects.
To see method chaining at a simple level, consider this example:
x = ‘hello’
y = x.capitalize().replace(‘e’, ‘a’)
print (y) # Prints ‘Hallo’
Because Python’s strings are immutable, a string method doesn’t alter the original string, rather it returns a new string. Therefore, adding a string method to the end of another string method means that the second method in the chain applies to the result of the first method’s execution, like this:
’hello’.capitalize().replace(‘e’, ‘a’)
‘Hello’.replace(‘e’, ‘a’)
‘Hallo’
We can achieve a similar effect with our IgnitionSwitch . Each method in the ignition sequence can be made to return the object it was passed, so the next method in the sequence can be tacked onto the end. For example, if the draw_power_to_coil method worked like this:
and all other engine parts worked along similar lines, the IgnitionSwitch could be simplified to look like this:
Many good books have been written on design patterns. Just a couple of them are:
Design Patterns (Gamma et al., 1995), the earliest book on the subject, although written in a rather advanced, cataloging style.
Design Patterns Explained (Shalloway and Trott, 2005), a more beginner-friendly text focused on explaining the concept in easily understandable stages.
Many design patterns exist and many good books describe them in detail. Each pattern may solve a different problem, but collectively their goals are the same: provide a reusable set of solutions to common design problems, simplify your programs, speed up development and give you a common terminology.
SUMMARY
The key pieces of advice when finding patterns in your program are: ‘Don’t repeat yourself’ and ‘find what varies and encapsulate it’. Programming languages like Python provide numerous built-in abstractions for encapsulating things (variables, functions, loops, etc.). Part of programming is to match parts of your solution to those built-in parts.
Another part of programming is using the language to build your own abstractions that your solution requires. In a language like Python, this is often done by creating your own types, each of which encapsulate some data and a set of operations and correspond to some part of your solution.
Patterns are found throughout all programs. Some that are not part of a language (but nevertheless often used) have been recognised and catalogued by many programmers over the years, providing you with a rich source of ready-made patterns.
EXERCISES
EXERCISE 1
Mark the following statements as true or false:
- All items in a Python list must have the same type.
- Creating a new object of a certain class is called instantiation.
- A subclass must override all the methods it inherits from the parent class.
- Reusing patterns helps to reduce effort when coming up with solutions.
- Design patterns are typically categorised into the following three categories: creational, structural and atypical.
EXERCISE 2
Write a Python program that prints out all the unique words in any arbitrary sentence. To keep things simple, it is assumed the sentence contains only letters and spaces (that is, no punctuation).
Hint : take advantage of a built-in type that automatically removes duplicates.
EXERCISE 3
In English, adjectives are expected to come in a certain order depending on type. The order is: opinion, size, quantity, quality, age, shape, colour, proper adjective (such as nationality), purpose. That’s why ‘the big, old, red, Italian racing car’ and ‘the pretty, little, old, red racing car’ sound right, but ‘the racing, red, old, big, pretty car’ sounds wrong. Using this rule, write an insult generator in Python that picks a random assortment of adjectives and orders them correctly in an insulting sentence (e.g. ‘disgusting, oversized, old, yellow handbag’).
EXERCISE 4
In the remaining questions, we’ll build a Rock-Paper-Scissors game. First, define a class for each of the three shapes: Rock , Paper , Scissors . Give each a method called beats , which takes another shape and returns whether it wins against the other shape or not.
EXERCISE 5
Add a class to act as a computer player. It should need only one method called choose , which returns one of the three random shapes.
Hint : if you import the package called random , you can access the random.choice() method, which returns a random item from a list.
EXERCISE 6
Add code to play one round of the game:
- The computer player should make a choice.
- The program should ask the player to choose a shape (ensuring that the input is valid).
- It should print out the computer’s choice.
- It should determine who won and print out the result.