gpt4 book ai didi

python - 单继承简单概念

转载 作者:行者123 更新时间:2023-12-01 09:16:22 25 4
gpt4 key购买 nike

class A:
a=10
b=20
class B(A):
print(b)
d=30
s=d+a
print(s)

在上面的程序中,解释器抛出了nameerror,但是根据继承的概念,程序是正确的。有人可以帮助我吗?

最佳答案

class A 中的变量 ab 类似于与类关联而不是与对象关联的静态变量。解决方案是在此处运行您的代码:

class A:
a=10
b=20
class B(A):
print(A.b)
d=30
s=d+A.a
print(s)

但是要清楚地理解它,请仔细查看下面的示例:

class A:
print("IN CLASS A.")
a = 10
b = 20

def __init__(self):
print("A's Constructor.")
self.x1 = 10
self.x2 = 20


print("Before making A's object")
a1 = A()
print("Attributes of class A:", A.__dict__)
print("Attributes of object:", a1.__dict__)
a1.a = 40
print("Attributes of class A:", A.__dict__)
print("Attributes of object:", a1.__dict__)


class B(A):
print("INSIDE CLASS B.")
print(A.b)
d = 30
s = d + A.a
print(s)

def __init__(self):
super().__init__()
print("B's Constructor.")
self.x3 = self.x1 + self.x2
print(self.x3)


print("Before making B's object")
b1 = B()

输出:

IN CLASS A.
Before making A's object
A's Constructor.
Attributes of class A: {'__module__': '__main__', 'a': 10, 'b': 20, '__init__': <function A.__init__ at 0x0000028FFC2F9158>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
Attributes of object: {'x1': 10, 'x2': 20}
Attributes of class A: {'__module__': '__main__', 'a': 10, 'b': 20, '__init__': <function A.__init__ at 0x0000028FFC2F9158>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
Attributes of object: {'x1': 10, 'x2': 20, 'a': 40}
INSIDE CLASS B.
20
40
Before making B's object
A's Constructor.
B's Constructor.
30

如果您想了解某些内容,请发表评论。

关于python - 单继承简单概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51221069/

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