python-3.x - 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
) 的属性。
解决方案
您编写的方式仅将这些值分配给局部变量。您需要初始化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"
推荐阅读
- css - 将段落文本放在 youtube 视频旁边?
- android - SearchView 未出现在浮动操作按钮上单击
- kdb - kdb:从表中删除所有行的最佳方法
- python - 对列表中连续递增的数字进行分组
- python - 在 Shell 中打印每个组合
- php - 目标类 [Api\UserController] 不存在
- typescript - 如何声明作为字符串枚举值联合的类型?
- crc - 识别 CRC 的多项式项
- google-kubernetes-engine - 在 ingress.yaml 中添加所需的 DNS 时,GKE 入口失败
- azure-data-explorer - Kusto 查询以最大 Z 获取每个 Y 中的 X