【问题标题】:How do I print methods of a class [closed]如何打印类的方法[关闭]
【发布时间】:2013-10-20 16:00:04
【问题描述】:

我已经搜索过,但找不到答案。

class Animal(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def description(self):
        print self.name
        print self.age

hippo = Animal('Alex', 12)
hippo.description

所以我的问题是我无法弄清楚如何调用描述我的 Animal 实例。我得到的只是None 返回,但它不会打印姓名和年龄。我尝试了多种方法,但结果都相同

【问题讨论】:

  • 你试过hippo.description()吗?

标签: python class methods attributes


【解决方案1】:

您需要通过在其后加上() 来调用该方法:

hippo.description()

见下文:

>>> class Animal(object):
...     def __init__(self, name, age):
...         self.name = name
...         self.age = age
...     def description(self):
...         print self.name
...         print self.age
...
>>> hippo = Animal('Alex', 12)
>>> hippo.description()
Alex
12
>>>

【讨论】:

  • 这解决了我的问题!谢谢!我不敢相信这是我没有尝试过的一件事。特别是因为这是我应该知道的。我只是感到困惑,因为我可以打印 hippo.name。但那是因为名字是河马的属性,对吧?既然描述是一种方法,那么它必须被调用?
  • 一定要调用吗?你读过 Python 基础教程吗?
  • 你知道什么是“方法”或“函数”吗?
  • 是的,我知道什么是函数。但是我现在才学习类和 python 的 OO 部分。我对方法和属性感到困惑,并且忽略了简单的东西。对不起这个问题。显然,提问会使人变得愚蠢,根本不允许犯错。
  • @EvolutionXJ - 不,忽略他。你的问题很好。事实上,在某些语言中,您不需要 () 来调用方法。是的,你可以打印hippo.name 的原因是它是一个属性,而不是一个方法。另一方面,description 是一个方法,必须被调用。
猜你喜欢
  • 1970-01-01
  • 2021-06-12
  • 1970-01-01
  • 2020-10-17
  • 2019-04-11
  • 2012-08-19
  • 1970-01-01
  • 1970-01-01
  • 2019-02-10
相关资源
最近更新 更多