gpt4 book ai didi

python - Python中的多重继承问题!

转载 作者:太空宇宙 更新时间:2023-11-03 13:23:50 24 4
gpt4 key购买 nike

为什么 c.print_a() 输出 'B'?

class A(object):
def __init__(self):
self.some_name = 'A'

def print_a(self):
print self.some_name

class B(object):
def __init__(self):
self.some_name = 'B'

def print_b(self):
print self.some_name

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

if __name__ == '__main__':
c = C()
c.print_a()

class A(object):
def __init__(self, some_name='A'):
self.some_name = some_name

def print_a(self):
print self.some_name

class B(object):
def __init__(self, some_name='B'):
self.some_name = some_name

def print_b(self):
print self.some_name

class C(A, B):
def __init__(self):
A.__init__(self, some_name='AAAAA')
B.__init__(self, some_name='BBBBB')

if __name__ == '__main__':
c = C()
c.print_a()

最佳答案

这里只有一个对象; some_name 属性在所有继承类的方法之间共享。您调用 A.__init__,将其设置为 A,然后调用 B.__init__,将其更改为 B .

另请注意,您错误地调用了基本方法;使用 super:

class A(object):
def __init__(self):
self.some_name = 'A'
super(A, self).__init__()

def print_a(self):
print self.some_name

class B(object):
def __init__(self):
self.some_name = 'B'
super(B, self).__init__()

def print_b(self):
print self.some_name

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

if __name__ == '__main__':
c = C()
c.print_a()

关于python - Python中的多重继承问题!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4677755/

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