How can I create a new Animal object and use its description method?
Remember, creating a new object of a class looks like this:
object_name = ClassName("arguments_here")
Then, to use the
description() method of our new
Animal, we simply call that method attached to our new object, like this:
Is this code correct? :
is_alive = True
def init(self, name, age):
self.name = name
self.age = age
Add your method here!
hippo = Animal(“Rick”, 50)
Because when the console gives me this output:
<bound method Animal.description of <Animal object at 0x7fc20418afd0>>
Shouldn’t it supposed to display the animal’s name and age?
Remove the print statement and add () after description. It should look like this:
hippo = Animal("Rick", 50)
The error probably appears since you forgot to include parentheses.
You don’t need the print statement because the function description already has them.
Thank you so much! Got it!
Another valid way of writing it is:
hippo = Animal("Hubert", 12)
Are the two ways of writing it merely a matter of taste, or is one way generally preferred over the other?
I don’t think it matters too much. The other way may be preferred since it is shorter, but your way could also be preferred, since it is more specific.
I’d like to know the use of “hippo.description()” here. Thanks
hippo.description() is a way of calling the method
description associated with the instance object referenced by
hippo. In this case it leads to a couple of attributes being printed to the console so it’s a quick way of returning particular pieces of data about that object.
If the method description is calling name and age why don’t we have to include those as arguments like this?
def description(self, name, age):
If you added them as arguments to the method then every time you called that method you’d have to pass those two additional arguments.
fossil = Animal("Seymour", 15)
fossil.description("Seymour", 15) # passing them every time isn't right
# fossil.description() # you want to be able to call it like this
Instead, because you have assignments for these objects in your
__init__ method, e.g.
self.name = name this data is already a bound attribute of any instance you create. So you can just use
self and access these attributes within the function making things much simpler.
hippo.description doesn’t print anything while
description consists of two print commands. Why?
Did you call it in the standard manner, e.g.
hippo.description() ? If so what does your
description method look like? If you’re posting code to the forums, please see: How do I format code in my posts?
() at the end of
hippo.description answered my question.
Yes. This is because
hippo.description implies that
description is a property (an instance variable) of
hippo. By adding
(), this means that
description() is a behaviour (an instance method) of
hippo. When we call methods, we need to add parentheses just as we would call a function.