Par*_*ham 4 python polymorphism
我一直在四处寻找最好的方法,但我还没有找到任何完全令人信服的东西.
我正在编写一个系统,其中包含用户对象和管理这些用户的集合.每个用户都有一个名称,我想在管理器中指定一个可以取用User名称或User对象本身的函数.
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)
Run Code Online (Sandbox Code Playgroud)
有没有任何漂亮的方式这样做或使用isinstance的方式去?
像mgilson这样的解决方案,但略有不同:
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)
Run Code Online (Sandbox Code Playgroud)
为什么?因为这样,AttributeErrors in remove()不会被抑制.
这可能是无关紧要的,但我更喜欢将异常处理集中在那些我真正想要拥有它们的地方.
| 归档时间: |
|
| 查看次数: |
9177 次 |
| 最近记录: |