Calling method in variable creation


#1


They're Multiplying.


Am I correct in assuming that if you run a method in the same line as the definition the definition doesn't hold it's value?

This exercise starts with this code:

class Animal(object):
    """Makes cute animals."""
    is_alive = True
    def __init__(self, name, age):
        self.name = name
        self.age = age
    # Add your method here!
    def description(self):
        print self.name
        print self.age
        
hippo = Animal("Hippo", 5).description()

Which returns the expected:

Hippo
5

However the task is to create two new Animal objects and print their "health" variables (please correct my terminology).

When I run:

class Animal(object):
    """Makes cute animals."""
    is_alive = True
    health = "good"
    def __init__(self, name, age):
        self.name = name
        self.age = age
    # Add your method here!
    def description(self):
        print self.name
        print self.age
        
hippo = Animal("Hippo", 5).description()

print hippo.health

(and the rest of the animals) I get

Traceback (most recent call last):
File "python", line 14, in
AttributeError: 'NoneType' object has no attribute 'health'

When it doesn't call the method in the creation line; it works :

hippo = Animal("Hippo", 5)

print hippo.health

Is there a reason for this ?


#2

well, if we call the method, we can simple see what is stored in hippo:

hippo = Animal("Hippo", 5).description()

print hippo

oops, none. Given your method only prints something, nothing gets returned or stored in hippo. While if you just do this:

hippo = Animal("Hippo", 5)

you can see a new instance of the object is stored in hippo:

print hippo

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.