Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用子对象访问父类中初始化的变量?_Python_Class - Fatal编程技术网

Python 如何使用子对象访问父类中初始化的变量?

Python 如何使用子对象访问父类中初始化的变量?,python,class,Python,Class,我有以下代码: class aa(object): def __init__(self): self.height = 12 class bb(aa): def __init__(self): self.weight = 13 AA = aa() BB = bb() 我正试图使用下面的子对象访问在父类(aa)中初始化的变量。 请建议正确的方法,因为我这样做会出错: (如果有人能给我提供一个关于Python子类化的好文档,那就太好了。) 必须从

我有以下代码:

class aa(object):
    def __init__(self):
        self.height = 12

class bb(aa):
    def __init__(self):
        self.weight = 13

AA = aa()
BB = bb()
我正试图使用下面的子对象访问在父类(aa)中初始化的变量。 请建议正确的方法,因为我这样做会出错:

(如果有人能给我提供一个关于Python子类化的好文档,那就太好了。)


必须从超类调用
\uuuu init\uuuu
。它不会被隐式调用

class bb(aa):
    def __init__(self):
        super(bb, self).__init__()
        self.weight = 13

您需要显式初始化超类。编辑
bb
\uuuuu init\uuuu
方法,使其如下所示:

class bb(aa):
    def __init__(self):
        super(bb, self).__init__()  # Call the __init__ method of the superclass.
        self.weight = 13
然后,它应该会起作用:

print AA.height  # 12
print BB.height  # 12


有关使用超类的文档,请参阅文档中的函数。

您可以在这里找到一个很好的示例:
print AA.height  # 12
print BB.height  # 12