首页 > 解决方案 > calling method in python to increase the age of the animal

问题描述

I have been assigned to create a dog named 'Molly' of age 1. I call the method grow to increase the age by 2 and print it.

I know how to make Molly run, but I am confused on how to increase her age, it keeps on showing None.

Any help will work, but it would be best if it could be explained. Thanks for your help in advance.

class Dog():
    """ a class representing a dog """

    def __init__(self, name, age):
        """ Initialize name and age attributes. """
        self.name = name
        self.age = age

    def run(self):
        """ Simulate a dog running. """
        print(self.name.title() + " is running ...")

    def grow(self, year):
        """ Update age by adding year. """
        self.age += year

molly = Dog("Molly", 1)

print(molly.name + " is " + str(molly.grow(2)))
molly.run()

The output of this is

Molly is None
Molly is running ...

标签: pythonpython-2.7classmethods

解决方案


grow方法不返回age属性,它只是设置age属性。

grow返回None(隐式),这就是您在print通话中看到的。

利用

print(molly.age) # 1
molly.grow(2) # adjust age
print(molly.age) # 3

看看我的意思。

您可以将原始尝试重写为

molly.grow(2)
print(molly.name + " is " + str(molly.age)) # Molly is 3

或者更优雅一点,字符串格式为

molly.grow(2)
print('{0.name} is {0.age}'.format(molly)) # Molly is 3

推荐阅读