我执行ChristmassTree()时为什么会得到两个字符串,但执行ct = ChristmassTree()时会出现一个字符串

时间:2016-12-01 17:07:25

标签: python-2.7

我刚刚开始研究面向对象的 Python ,所以我有这个问题。

首先,我创建了这些类:

class Tree:
count = 0

def __init__(self, name, age):
    self.name = name
    self.age = age
    Tree.count += 1

def displayTree(self):
    print "Total amount of Trees: %d"% Tree.count

class ChristmasTree(Tree):
    def __init__(self):
        Tree.count += 1
        print "I am a ChristmasTree. I am the most beautiful among %d"% Tree.count + " trees"

所以,我不明白为什么在执行这个命令时会看到两个字符串:

ChristmasTree()

输出:

I am a ChristmasTree. I am the most beautiful among {variable} trees
<Tree.ChristmasTree instance at 0x00000000002209788>

但是当我执行这个命令时我得到一行:

ct = ChristmasTree()

输出:

I am a ChristmasTree. I am the most beautiful among {variable} trees

根据我的逻辑,应该有一行输出:

I am a ChristmasTree. I am the most beautiful among {variable} trees

我哪里错了?

2 个答案:

答案 0 :(得分:0)

我不知道你在这里要做什么。但至少,您需要在Tree.__init__(name,age)的{​​{1}}方法中致电ChristmasTree

答案 1 :(得分:0)

当您在没有为输出指定名称的情况下调用函数时,输出将显示为#34;,即将调用其__repr__(self)方法。默认设置是返回实例的内存地址but you can overwrite it with a __repr__ method of your own.