单继承简单概念

时间:2018-07-07 07:43:06

标签: python python-3.x

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

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

1 个答案:

答案 0 :(得分:1)

a中的变量bclass A就像是与类而不是对象相关联的静态变量。在这里运行代码是解决方案:

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

评论,如果您想了解一些东西。