【发布时间】:2016-06-20 04:06:27
【问题描述】:
来自 Java,我在理解 Python 中的 OO 编程的继承、抽象类、静态方法和类似概念时有点吃力。
我有一个表达式树类的实现,由
给出(简化)# Generic node class
class Node(ABC):
@abstractmethod
def to_expr(self):
pass
@staticmethod
def bracket_complex(child):
s = child.to_expr()
return s if isinstance(child, Leaf) or isinstance(child, UnaryOpNode) else "(" + s + ")"
# Leaf class - used for values and variables
class Leaf(Node):
def __init__(self, val):
self.val = val
def to_expr(self):
return str(self.val)
# Unary operator node
class UnaryOpNode(Node):
def __init__(self, op, child):
self.op = op
self.child = child
def to_expr(self):
return str(self.op) + super().bracket_complex(self.child)
# Binary operator node
class BinaryOpNode(Node):
def __init__(self, op, lchild, rchild):
self.op = op
self.lchild = lchild
self.rchild = rchild
def to_expr(self):
return super().bracket_complex(self.lchild) + " " + str(self.op) + " " + super().bracket_complex(self.rchild)
# Variadic operator node (arbitrary number of arguments)
# Assumes commutative operator
class VariadicOpNode(Node):
def __init__(self, op, list_):
self.op = op
self.children = list_
def to_expr(self):
return (" " + str(self.op) + " ").join(super().bracket_complex(child) for child in self.children)
在Leaf、UnaryOpNode 和BinaryOpNode 的实例上调用to_expr() 方法可以正常工作,但在VariadicOpNode 的实例上调用时会引发TypeError:
TypeError: super(type, obj): obj must be an instance or subtype of type
我在 super() 突然无法工作的特定课程中做错了什么?
在 Java 中,静态方法会被继承,所以我什至不需要 super 调用,但在 Python 中似乎不是这样。
【问题讨论】:
-
您使用的是 Python2 还是 Python 3? docs.python.org/2/library/functions.html#super
-
@Jasper 因为他使用
super没有参数,所以我相信他使用的是python3.3+。 -
题外话:你为什么在
to_expr中使用super()来调用bracket_complex?你应该使用self,否则你可能会在覆盖bracket_complex的子类中引入问题 -
正如标题所述,我使用的是 Python 3。在 Bakuriu 下面的回答之后,我已经修复了 super() -> self 问题。
标签: python inheritance typeerror superclass super