How can I create a new Animal object and use its description method?
Answer
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: object_name.method_name()
Remove the print statement and add () after description. It should look like this:
hippo = Animal("Rick", 50)
hippo.description()
The error probably appears since you forgot to include parentheses.
You don’t need the print statement because the function description already has them.
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.
Using 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 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.
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?
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.