首页 > 解决方案 > Python3 super 没有初始化 __init__ 属性

问题描述

我有以下代码片段:

class BaseUserAccount(object):
    def __init__(self):
        accountRefNo = "RefHDFC001"
        FIType = "DEPOSIT"
        pan = "AFF34964FFF"
        mobile = "9822289017"
        email = "manoja@cookiejar.co.in"
        aadhar = "5555530495555"


class TestUserSavingsAccount(BaseUserAccount):
    def __init__(self):
        super().__init__()
        accountNo = "HDFC111111111111"
        accountTypeEnum = "SAVINGS"

    def test_create_account(self):
        request_body = """\
            <UserAccountInfo>
                <UserAccount accountRefNo="{}" accountNo="{}"
                accountTypeEnum="{}" FIType="{}">
                    <Identifiers pan="{}" mobile="{}" email="{}" aadhar="{}"></Identifiers>
                </UserAccount>
            </UserAccountInfo>
        """.format(self.accountRefNo, self.accountNo, self.accountTypeEnum,
                self.FIType, self.pan, self.mobile, self.email, self.aadhar)

如果我在交互式 shell 中运行此代码:

>>> t = TestUserSavingsAccount()
>>> t.accountRefNo
AttributeError: 'TestUserSavingsAccount' object has no attribute 'accountRefNo'
>>> t.accountNo
AttributeError: 'TestUserSavingsAccount' object has no attribute 'accountNo'

看到上述行为,似乎super既没有从基类设置值,也没有设置子 ( accountNo, accountTypeEnum) 的属性。

标签: python-3.xinheritancesuper

解决方案


您编写的方式仅将这些值分配给局部变量。您需要初始化self对象的属性:

class BaseUserAccount(object):
    def __init__(self):
        self.accountRefNo = "RefHDFC001"
        self.FIType = "DEPOSIT"
        self.pan = "AFF34964FFF"
        self.mobile = "9822289017"
        self.email = "manoja@cookiejar.co.in"
        self.aadhar = "5555530495555"


class TestUserSavingsAccount(BaseUserAccount):
    def __init__(self):
        super().__init__()
        self.accountNo = "HDFC111111111111"
        self.accountTypeEnum = "SAVINGS"

推荐阅读