Python:从一个类继承,子类给出TypeError

时间:2012-08-03 00:59:04

标签: python inheritance

我有两个类从同一个基类继承,但不想互相玩,确实是年轻的类。

class A() : 
  ...

class B(A) : 
  ...

class C(A) : 
  ...

b=B()
c=C()
c.method(b)

给我一​​个c和b的TypeError不一样,python需要认为它们是一样的吗?是否应该实现一些__SpecialThingIDontKnowAbout__属性/方法?或者是否有一些我缺少的课堂设计技巧

特别是我继承TreeDict()如下:

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)

给出

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'

我确实知道孩子们是'类型','treedict ^ 3'是必需的,但我如何让孩子模仿这种行为?

编辑:

嗯......它现在开始工作了,而不是我在撤消/重做历史中做了什么不同(全部谢谢)

1 个答案:

答案 0 :(得分:1)

问题是TreeDict类型不允许子类化。我在treedict包中找到了它。 TreeDict类型本身是用Cython编写的。罪魁祸首是attach()方法中的这段代码(在treedict.pyx的1910行左右):

    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.")

elif type(tree_or_key) is TreeDict:行更改为elif isinstance(tree_or_key, TreeDict):并向项目提交补丁。你可能想检查其余的treedict.pyx是否存在同一个bug。