gpt4 book ai didi

python - Python 中的函数多态性

转载 作者:太空狗 更新时间:2023-10-30 01:52:00 26 4
gpt4 key购买 nike

我一直在四处寻找最好的方法,但我还没有真正找到任何完全令人信服的方法。

我正在编写一个系统,其中包含用户对象和管理这些用户的集合。每个用户都有一个名称,我想在管理器中指定一个函数,该函数可以采用用户的名称或用户对象本身。

class UserManager: 
def remove_user(self,user_or_username):
#If user_or_username is a string
remote.remove(user_or_username)
#If user_or_username is a User object
remote.remove(user_or_username.name)

是否有任何巧妙的方法可以做到这一点,或者使用 isinstance 是可行的方法吗?

最佳答案

类似 mgilson's 的解决方案, 但略有不同:

def remove_user(self,user_or_username):
try:
#If user_or_username is a User object
username = user_or_username.name
except AttributeError: #Oops -- didn't works. ask forgiveness ;-)
#If user_or_username is a string
username = user_or_username
remote.remove(username)

为什么?因为这样,remove() 中的 AttributeError 不会被抑制。

这可能无关紧要,但我更喜欢将异常处理集中在那些我真正想要拥有它们的地方。

关于python - Python 中的函数多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10601114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com