Exercise 42 doesnât go in much details about building functions inside of classes. I think Zed mainly wants you to distinguish between a class and an object.
Later on, in exercise 44d and 44e you will start seeing on how to use functions within classes. So I wouldnât treat myself too hard on learning the relationship between classes and functions just yet.
However, if you want to get your code working, you could use this next code as a reference:
In regards of ex40.py
class foo(object):
# 1.foo has-a attribute named bar.
def __init__(self, bar):
self.bar = bar
# function prints the attribute inside the print stateme
def print_bar(self):
print(self.bar)
You create a variable named âstuffâ which is an instance of the âfooâ class and âtestâ is given as argument in reference to âbarâ:
stuff = foo("test")
You can now use the functions from the âfooâ class within your variable stuff:
stuff.print_bar()
Now the previous will print:
test
because that is what is referenced to the
attribute âbarâ which is inside the
.print_bar()
function.
In regards of ex42.py
Parent class:
class Animal(object):
def __init__(self, animal):
self.animal = animal
Cat class now inherited functionalities from the Animal class:
class Cat(Animal):
def __init__(self, name):
# Cat has-a attribute named name
self.name = name
satan = Cat("Satan")
Person class now inherited functionalities from the Animal class
class Person(Animal):
# Person has-a name and a pet attribute
def __init__(self, name):
# self has-a name as name
self.name = name
# Person has-a pet of some kind
self.pet = None
def pet_name(self, name):
print(self.name, "has a pet named", name)
mary = Person("Mary")
mary.pet = satan.name
mary.pet_name(mary.pet)
That should print:
Mary has a pet named Satan