Python面向对象:如何正确实现Person类的check_integrity校验方法?
问题分析
原check_integrity方法存在几个核心逻辑错误:
- 校验逻辑顺序错误:将Person本身的属性校验(年龄、姓名)放在了账户遍历循环中,每次遍历都会重复判断,且只要第一个账户走完判断就直接返回结果,不会校验剩余所有账户
- 账户归属判断错误:
v.owner == Person()是和新生成的空Person实例做比对,完全不符合「账户owner必须是当前Person实例」的要求 - 返回逻辑错误:只要第一次遍历的账户满足错误的判断条件就返回True,没有确认所有规则是否全部满足
正确实现
from typing import List class Person(): def __init__(self, person_id: int, name: str, age: int, accounts: List['Account']): self.person_id = person_id self.name = name self.age = age self.accounts = accounts def check_integrity(self) -> bool: # 先校验Person本身的两个规则,若需要排除全空白姓名可将self.name == ''替换为self.name.strip() == '' if self.age < 18 or self.name == '': return False # 遍历所有持有的账户校验归属 for account in self.accounts: if account.owner != self: return False # 所有规则全部满足才返回True return True class Account(): def __init__(self, account_id: int, password: str, balance: int, limit:int, owner: Person): self.account_id = account_id self.password = password self.balance = balance self.limit = limit self.owner = owner
逻辑说明
- 优先校验Person自身的属性规则:年龄不满18、姓名为空直接返回False,不需要再做后续账户校验
- 遍历所有持有的账户,只要有一个账户的owner不是当前Person实例,就返回False
- 所有校验规则全部通过后,才最终返回True
内容的提问来源于stack exchange,提问作者GGGGGG
相关产品推荐
相关产品推荐

