Python: Inheriting from a single class, child classes give a TypeError

I have two classes that inherit from the same base class but do not want to play with each other, such as young ones.

class A() : ... class B(A) : ... class C(A) : ... b=B() c=C() c.method(b) 

gives me TypeError c and b, not the same thing python needs to think they are the same? Is there any __SpecialThingIDontKnowAbout__ property / method that needs to be implemented or not? Or is there some trick for class design that I am missing

To be specific, I inherit TreeDict () as follows:

 class TNode(TreeDict): def __init__(self,*args,**kwargs) : super(TNode, self).__init__(*args, **kwargs) class LNode(TreeDict): def __init__(self,*args,**kwargs) : super(LNode, self).__init__(*args, **kwargs) TN = TNode(); TN.A = 1 LN = LNode(); LN.A = 1 LN.attach('TN',TN) 

gives

 Traceback (most recent call last): File "JSONE.py", line 430, in <module> LN.attach(TN) TypeError: descriptor 'attach' requires a 'treedict.treedict.TreeDict' ... object but received a 'type' 

I understand that children have type and treedict ^ 3, but how do I get children to mimic this behavior?

EDIT:

Hmm ... it started working now, and not that I did something different from what I see in the undo / redo history (thanks to everyone)

+4
source share
1 answer

The problem is that the TreeDict type does not allow subclassing. I found it in the treedict package. The TreeDict type itself is written in Cython. The culprit is this block of code in the attach() method (around line 1910 of the treedict.pyx file):

  if type(tree_or_key) is str: key = <str>tree_or_key elif type(tree_or_key) is TreeDict: if tree is not None: raise TypeError("Only one TreeDict instance can be given to attach.") tree = <TreeDict>tree_or_key key = None else: raise TypeError("`tree_or_key` must be either a string or TreeDict instance.") 

Change the line elif type(tree_or_key) is TreeDict: to elif isinstance(tree_or_key, TreeDict): and send the patch to the project. You might want to check out the rest of treedict.pyx for other occurrences of the same error.

+1
source

All Articles