【问题标题】:calling method in python to increase the age of the animal在python中调用方法来增加动物的年龄
【发布时间】:2019-05-26 15:43:28
【问题描述】:

我被指派创建一只名叫'Molly' 的狗,年龄为1。我调用grow方法将年龄增加2并打印出来。

我知道如何让 Molly 跑步,但我对如何增加她的年龄感到困惑,它一直显示None。

任何帮助都会起作用,但最好能解释一下。提前感谢您的帮助。

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()

这个的输出是

Molly is None
Molly is running ...

【问题讨论】:

  • 您使用print 的方式建议使用Python 3,但您标记了python-2.7。是哪个?

标签: python python-2.7 class methods


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 2017-08-08
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多