Python3 super 未初始化 __init__ 属性

Python3 super not initializing __init__ attributes

我有以下代码片段:

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 既没有设置基础 class 的值,也没有设置 child 的属性(accountNoaccountTypeEnum) 正在设置中。

你写的方式只将这些值分配给局部变量。您需要初始化 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"