I’m going through Learn Python the Hard Way 2nd Edition and I’ve just done the exercise where am suppose to write down the is-a/has-a relationships. Am able to use classes somehow but i find is-a/has-a confusing. So I have no ideas if what I’ve done is correct, any pointers will be appreciated. Thanks.
## Animal is-a object (yes, sort of confusing) look at the extra credit
class Animal(object):
pass
## ?? Dog is-a object
class Dog(Animal):
def __init__(self, name):
## ?? Dog has-a name
self.name = name
## ?? Cat is-a object
class Cat(Animal):
def __init__(self, name):
## ?? Cat has-a name
self.name = name
class Person(object):
def __init__(self, name):
## ?? Person has-a name
self.name = name
## Person has-a pet of some kind
self.pet = None
## ?? Employee is-a object
class Employee(Person):
def __init__(self, name, salary):
## ?? hmm what is this strange magic?
super(Employee, self).__init__(name)
## ?? Employee has-a salary
self.salary = salary
## ?? Fish is-a object
class Fish(object):
pass
## ?? Salmon is-a object, type of a fish
class Salmon(Fish):
pass
## ?? Halibut is-a object, type of a fish
class Halibut(Fish):
pass
## rover is-a Dog
rover = Dog("Rover")
## ?? satan is-a Cat
satan = Cat("Satan")
## ?? mary is-a person
mary = Person("Mary")
## ?? mary has-a pet called satan
mary.pet = satan
## ?? frank is-a Employee on 120000 salary
frank = Employee("Frank", 120000)
## ?? frank has-a pet called rover
frank.pet = rover
## ?? flipper is Fish
flipper = Fish()
## ?? crouse is-a Salmon
crouse = Salmon()
## ?? harry is-a Halibut
harry = Halibut()
So you are close. I remember struggling with the OOP paradigm at first also, especially after learning some c. Anyway, OOP is really more common sense than it may seem… The only tricky bit here is the first one, which was given to you… Animal is an Object.
While you are correct that Dogs, Cats, and Employees are objects, they are more importantly Animals, Animals, and People respectively.
This exercise is really about a property of OOP, inheritance. For instance, the class hierarchy for Dog:
Object -> Animal -> Dog
A dog is both an Animal and an Object, and it ‘has’ all of the properties of both. Now the properties can be overridden in subclasses, but that’s for later discussion.
I think you started to get this around the Halibut and Salmon section. They are both Objects and Fish.
The last bit I would say, is:
Frank is an Employee (and Person and Object) whose name is Frank and has a salary of 120000.
I hope that helped.