In: Computer Science
This task is about classes and objects, and is solved in Python 3.
We will look at two different ways to represent a succession of monarchs, e.g. the series of Norwegian kings from Haakon VII to Harald V, and print it out like this:
King Haakon VII of Norway, accession: 1905
King Olav V of Norway, accession: 1957
King Harald V of Norway, accession: 1991
>>>
Make a class Monarch with three attributes: the name of the monarch, the nation and year of accession. The class should have a method write () which prints out the information on a line like in the example. It should also have the method _init_ (…), so that you can create a Monarch instance by name, nation and year of accession as arguments. Example:
haakon = Monarch("Norway","King Haakon VII",1905)
Here, the variable haakon will be assigned to the Monarch object for King Haakon VII. Now the series of kings can be represented in a variable series of kings, that contains a list of the three monarchs, in the right order. Finally, the program will print the series of kings as shown above.
class Monarch():
def __init__(self,name,nation,year):
self.name=name
self.nation=nation
self.year=year
def write(self):
print('King {} of {}, accession:
{}'.format(self.name,self.nation,self.year))
haakon = Monarch("Norway","King Haakon VII",1905)
olav = Monarch("Norway","King Olav V",1957)
harald = Monarch("Norway","King Harald V",1991)
haakon.write()
olav.write()
harald.write()