0

While I was framing the Title question I saw this https://stackoverflow.com/questions/23642105/attributeerror-list-object-has-no-attribute-trackprogress and AttributeError: 'list' object has no attribute 'display' in python

but unlike those questions, this is similar to Can't set attributes of object class and not duplicate if and only if list doesnt behave like Object (reserved,read only attr)

I am able to set self.root and for the sake of checking self.rightChild & self.leftChild so why does it throw this error?

class BinaryTree(list):
    ...:     def __init__(self,root_val,**kwarg):
    ...:         super(type(self),self).__init__()
    ...:         self.root = root_val
    ...:         self.rightChild = self.leftChild = None
    ...:         self = binaryTree(self.root)
    ...:         if 'left_child' in kwarg:
    ...:             self.leftChild = kwarg['left_child']
    ...:         if 'right_child' in kwarg:
    ...:             self.rightChild = kwarg['right_child']
    ...:             

b = BinaryTree(4,left_child = 5,right_child = 6)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-67-3ea564fafb06> in <module>()
----> 1 b = BinaryTree(4,left_child = 5,right_child = 6)

<ipython-input-66-208c402b07ce> in __init__(self, root_val, **kwarg)
      6         self = binaryTree(self.root)
      7         if 'left_child' in kwarg:
----> 8             self.leftChild = kwarg['left_child']
      9         if 'right_child' in kwarg:
     10             self.rightChild = kwarg['right_child']

AttributeError: 'list' object has no attribute 'leftChild' 

binaryTree is some foo() function that works well and is not at all the concern.

Community
  • 1
  • 1
user2290820
  • 2,709
  • 5
  • 34
  • 62

2 Answers2

2

Apparently binaryTree returns a list, not a BinaryTree. So after the line self = binaryTree(self.root), self is now a list and self.leftChild = ... thus produces an error as you cannot do that to a list.

binaryTree is [...] not at all the concern

I'm pretty sure you're wrong about that.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
1

Change class BinaryTree(list): to class BinaryTree(object):. There's no need to base your tree object off of the list class.

(Also, overwriting self is probably not what you want to do. You probably instead want to assign to a subattribute of self.)

Amber
  • 507,862
  • 82
  • 626
  • 550