Classes


#1

in this example
class Animal(object):
"""Makes cute animals."""
is_alive = True
def init(self, name, age):
self.name = name
self.age = age

zebra = Animal("Jeffrey", 2)
giraffe = Animal("Bruce", 1)
panda = Animal("Chad", 7)

print zebra.name, zebra.age, zebra.is_alive
print giraffe.name, giraffe.age, giraffe.is_alive
print panda.name, panda.age, panda.is_alive

Why is_alive isn't in the def init (...)? I know that is_alive is a member variable,but I don't undestand why in the output he managed to put true/false.


7 - Class Scope
#2

Thing is, the output doesn't have any "False" in there, does it? They're all true.

As to the reason why it's not in init is explained in the exercise text:

each individual animal gets its own name and age (since they're all initialized individually), but they all have access to the member variable is_alive, since they're all members of the Animal class.

The name and age variables are specific to each individual animal, while all of them share the exact same value for is_alive, "True". It's a bit of an odd example, but the code assumes that all animals must be alive at all times. If they die they apparently cease to be an animal :wink:

EDIT:
Disregard that! Exercise 9 proves me wrong!

hippo = Animal("Jake", 12)
cat = Animal("Boots", 3)
print hippo.is_alive       #True
hippo.is_alive = False
print hippo.is_alive       # False
print cat.is_alive           # True

The is_alive variable is in fact unique for each critter as well. In that case let me assume that they do not want the value for is_alive to be up for discussion at the moment of instantiation. Whenever a new animal is registered, it will always be assumed to be alive. I guess that's what's going on here.