python - 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 ...
解决方案
该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
推荐阅读
- java - 使用 Spring Boot 和 Liquibase 时如何在每次集成测试后清理数据库表?
- c++ - 复制几乎为空的数组的最快方法
- c# - 如何在 Xamarin 中指定哈希算法?
- google-cloud-platform - GCP 私有集群的 Terraform 代码不起作用
- c# - 无法获取 JSON.NET 架构来查找我的外部引用的 JSON 架构文件
- dns - Azure URL 不适用于新的 CNAME 条目
- node.js - Angular 10 如何修复警告:(节点:27976) ExperimentalWarning:fs.promises API 是实验性的
- python - 目前如何在 Pygame 中播放视频?
- flutter - Flutter statelessWidget 初始化 viewModel
- python - 如何在 python 中将 Xpath 变成循环?