Python 如何打印类的方法

Python 如何打印类的方法,python,class,methods,attributes,Python,Class,Methods,Attributes,我已经找过了,找不到答案 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 所以我的问题是,我不

我已经找过了,找不到答案

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

所以我的问题是,我不知道如何将描述称为我的动物实例。我得到的只是返回的
None
,但它不会打印姓名和年龄。我尝试了多种方法,但都有相同的结果

您需要将
()
放在方法后面来调用该方法:

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.description()
?解决了我的问题!谢谢我不敢相信这是我没有尝试过的一件事。特别是因为这是我应该知道的。我只是感到困惑,因为我可以打印河马的名字。但那是因为名字是河马的一个属性,对吗?既然描述是一种方法,那么它必须被调用?它必须被调用?你读过基本的Python教程吗?你知道什么是“方法”或“函数”吗?是的,我知道函数是什么。然而,我刚刚学习了类和python的OO部分。我对方法和属性感到困惑,忽略了简单的东西。很抱歉问你这个问题。显然,问问题会让人变得愚蠢,错误是绝对不允许的。@EvolutionXJ-不,别理他。你的问题很好。事实上,在某些语言中,调用方法不需要
()
。是的,您可以打印
hippo.name
的原因是它是一个属性,而不是一个方法<另一方面,代码>说明是一种方法,必须调用。