从子类(Python)访问类属性?

从子类(Python)访问类属性?,python,class,inheritance,subclass,Python,Class,Inheritance,Subclass,以下是我的代码格式: 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是我想调用的一个对象,后面有一个下标(

以下是我的代码格式:

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\u other
中)

我只希望从父类继承
x
。 重要的是不要继承
other
,因此
super()。\uuuu init\uuuu
不合适

我已尝试通过在
a类
中创建函数来解决此问题:

def x(self):
    return self.x
所以我可以在
类B
中调用
super().x()
,但这也不起作用

我试图直接调用super.x[“foo”],但这不起作用

我如何才能在我的情况下实现我想要的?
谢谢!

变量不必总是在
\uuuu init\uuuu
函数中注册,如果您想从类
A
中注册
x
,请在
A
中使用一个方法:

def x(self):
    return self.x
def set_x(self, x):
    self.x = x
    # other stuff

由于所有函数都是继承的,您仍然可以从类
B
调用
set\ux
,从那里您可以实例化属性
x
,而无需从
A
调用
\uu初始化
,如果您不想继承某些东西,您的类层次结构是错误的。但是,在我继承整个x函数的情况下打开(请参见第二块代码),下标它不能按预期工作。当你下标一个函数时,你希望得到什么?它不是一个可下标的对象。为什么继承
其他
是一个问题?如果你不想使用它,你就不能忽略它吗?@Prune这正是我的问题,我想下标
self.x
,定义在同样。由于您不能在
A
中使用
\uuuu init\uuuu
函数,只需在
A
中使用不同的函数来设置
x
,然后在实例化B的实例后,您可以从
B.\uu init\uuu>调用
self.set\ux()
,因为该函数是继承的。