既然我已经继承了基类,为什么选择“AttributeError”?

2024-10-03 11:23:30 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,我是新手。你知道吗

class A(object):
    def __init__(self, idn, name):
        self.idn = idn
        self.name = name


class B(object):
    def __init__(self, idn, acc_no, criminal_case='No'):
        self.idn = idn
        self.acc_no = acc_no
        self.criminal_case = criminal_case

    def get_info(self):
        return self.idn

class C(A, B):
    pass


c = C(1, 'xyz')
print c.get_info()
print c.criminal_case

回溯(最近一次呼叫):

“文件”tp.py公司,第25行,在

打印刑事案件

AttributeError:“C”对象没有“刑事案件”属性


Tags: nonameselfinfogetobjectinitdef
2条回答

没有super()几乎不可能使用多重继承,因此您需要使用super()。你知道吗

super()

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.

您的代码应该是这样的:

   class A(object):
        def __init__(self, idn, name):
            super(A, self).__init__(idn, name,'test')
            self.idn = idn
            self.name = name

您将得到输出:

1
test

在python3.x中,您可以只使用super().__init__(),而且似乎您正在使用python2.x,所以您需要使用super(A, self).__init__(idn, name)。你知道吗

希望这有帮助。你知道吗

Python不会为继承层次结构中的每个类调用__init__()。相反,它只是在层次结构中搜索first__init__()并运行它。在代码中添加一些print语句,以便自己查看。你知道吗

要从A调用B.__init__,您需要按照以下思路自己调用super()。你知道吗

super(A, self).__init__(idn, None)

但这并没有什么意义:acc_no的值应该来自哪里?也许你应该重新审视你的课堂设计。你知道吗

相关问题 更多 >