【发布时间】:2019-04-02 21:43:34
【问题描述】:
这是我的代码格式:
class A(object):
def __init__(self, x, other):
self.other = other
self.x = x
class B(A):
def __init__(self):
# place code here
def something_else(self):
return self.x["foo"]
x 是我想调用的对象,稍后带有下标(在something_else 中。
我只想从父类继承x。
重要的是other不被继承,所以super().__init__不适合。
我已尝试通过在class A 中创建一个函数来解决此问题:
def x(self):
return self.x
所以我可以在class B 中调用super().x(),但这也不起作用。
我曾尝试直接拨打super.x["foo"],但不起作用。
我怎样才能在我的情况下实现我想要的? 谢谢!
【问题讨论】:
-
如果你想不继承一些东西,你的类层次结构是错误的。
-
不过,在我继承整个 x 函数的情况下(参见第二个代码块),下标它并不能按预期工作。
-
当你下标一个函数时你期望得到什么?它不是可下标的对象。
-
为什么
other被继承是个问题?不想用,就不能直接忽略吗? -
@Prune 这正是我的问题,我想在 A.__init__() 中定义
self.x下标。
标签: python class inheritance subclass