开发者

How to build a binary tree from down to top?

开发者 https://www.devze.com 2023-03-20 17:35 出处:网络
I am trying to build a tree. I´m begging with the next piece of code: >>> class tree: def __init__(self, charge, left=None, right=None):

I am trying to build a tree. I´m begging with the next piece of code:

>>> class tree:
    def __init__(self, charge, left=None, right=None):
 开发者_StackOverflow社区       self.charge = charge
        self.left = left
        self.right = right

>>> class tree:
    def __str__(self):
        return str(self.charge)

After writing that I write the next

>>> left = tree(2)

I write this because its what is supposed to do as the manual I am using teach. However I get this error:

Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
left = tree(2)
TypeError: this constructor takes no arguments

How can I build a tree with the code of the beginning from down to top? By the way my python version is 2.7.2


You are defining a class and then redefining it. Every time you say class tree: you create a new class definition, overwriting the previous one. Since the last definition of tree doesn't define an __init__ method, it doesn't take any arguments.

The fact that you are doing this in the interactive interpreter complicates things, because any time you type in a blank line, you end whatever definition you are working on. You might be better off, when it comes to classes, simply editing a text file mytree.py and then typing >>> import mytree.

Also, if the manual you are using suggests class foo: as the way to define classes, and it's about Python 2, then it is a very old manual. When using up-to-date versions of Python 2, you should do this:

class Tree(object):
    def __init__(self, ...)
    ...

As delnan points out, you don't need to explicitly inherit from object in Python 3, so you can leave the parenthesis empty. Indeed, you can omit them entirely; my eye misses the parens when they're absent, but Dive Into Python 3 doesn't include them at all.

0

精彩评论

暂无评论...
验证码 换一张
取 消