gpt4 book ai didi

python - 如何在python中访问父类的实例变量?

转载 作者:行者123 更新时间:2023-11-28 21:45:41 26 4
gpt4 key购买 nike

我想访问父类构造函数中定义的类变量。这是代码。

class A(object):
def __init__(self):
x = 0

class B(A):
def __init__(self):
super(B, self).__init__()

def func(self):
print self.x

s = B()
s.func()

这给我错误:

AttributeError: 'B' object has no attribute 'x'

如果我尝试将 func() 更改为

def func(self):
print x

然后我得到错误:

NameError: global name 'x' is not defined

如果我尝试将 func() 更改为

def func(self):
print A.x

然后我得到错误

AttributeError: type object 'A' has no attribute 'x'

现在我的思路已经用完了。在父类 A 中访问该类变量 x 的正确方法是什么?谢谢!

注意:我只处理项目的“B 类”部分,因此我不能真正去修改 A 类并更改变量的定义方式。这是唯一的限制。

最佳答案

必须是self.x,而不仅仅是x:

class A(object):
def __init__(self):
self.x = 0

只是一个简短的说明 - 即使从 A 的其他方法也将是 x 不可访问:

class A(object):
def __init__(self):
x = 0
def foo(self):
print(self.x) # <- will not work
print(x) # <- will utimately not work

关于python - 如何在python中访问父类的实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39057964/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com