单一继承简单概念


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

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

class Aab的变量就像与类而不是对象关联的静态变量。要运行您的代码,这里是解决方案:

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

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

最新更新