Python Week 5
6 March 2018
Python Week 5 Challenges
This week you've learnt about creating your own types, known as classes or objects. The following are all doable by just what Lloyd has covered, but of course, if you feel like going out on your own and trying to find other ways, feel free to do so!
First, create a class called "Person". You should remember that whenever you as the programmer wants to create an instance of an object, you use what's known as a "constructor". In Python, the constructor method is known as "__init__", as can be thought of as a function inside the class that you define yourself.
Have a think about what data you might want a Person object to include (obviously, you might want a name, but what else can you think of?). Try having a play around with creating a few of your own
Person instances (with different attributes/names, for example).
Next, implement a
greet() method inside the class such that when called on an instance, it would print out a greeting (e.g. "Hello! My name is ___!").
Let's get a little more advanced now!
First, notice that if we had a variable called
me that is a
Person object, calling
print(me) isn't actually that helpful...
To fix this, look into implementing a
__str__ method for the
Person class. Google will be your friend here, but it should be a pretty straightforward task once you look around a little bit. Once you successfully do that, test it and make sure it works as you want!
We might want to model the relationships between people. For example, married couples. How could you represent that a
Person whose name is "Lloyd" is married to another
Person called "George"? Hint: You might want to consider adding a field in the
Person class that links to their partner, and creating a method
set_partner that sets that field to another
Person. Also, keep in mind that if A is married to B, then obviously B is married to A as well.
To further complicate things even more, you might want your
Person objects to have parents and children as well. Try implementing methods
add_children. The design is completely up to you, however, we recommend using a
list to keep track of both - though keep in mind a
Person can only have up to 2 parents!
Extra Hard: Now that we've implemented a form of looking at
Person's "Family Tree", have a go at one of the following:
- Writing a class method which calculates the total number of descendants of a
Person. Hint: You're probably going to want to do this recursively.
- Writing a function which, given two
Personobjects, calculates how 'far' away they are related. For example, if they are siblings or one is a parent of another, then the answer should be 1. Grandparent-grandchild should return 2, and etc. If they are not related at all, then return 0. Hint: You're ALSO probably going to want to do this recursively.