7 - Class Scope


#1

I'm confused on why is_alive is define as a member variable(I think it's a member variable) and not passed as an argument to the initfunction:

Why this?

class Animal(object):
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

and not this?

class Animal(object):
def init(self, name, age, is_alive):
self.name = name
self.age = age
slef.is_alive = is_alive

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

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


#2

Well, if you throw it into the __init__ and then inherit the class and then overrride said __init__ you would not have that member variable if you did not inherit the base classes' __init__.

Though, I do not see much use in that it is a possibility.


#3

As I wrote in another forum thread, I reckon it boils down to this:

[I] 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.

Would be a bit creepy to add: kangaroo = Animal("Joey", 2, False) to your zoo, eh? Unless we're keeping a stuffed exhibit as well.