Python 寻找更好的方法来检查实例属性并根据属性类型指定值

Python 寻找更好的方法来检查实例属性并根据属性类型指定值,python,introspection,praw,Python,Introspection,Praw,我正在使用praw模块,我发现我的对象有时有一个属性subreddit,它有时是一个字符串,有时是一个具有自己属性的对象。我用以下方法处理了它: for c in comments: if isinstance(c.subreddit, str): subreddit_name = c.subreddit else: subreddit_name = c.subreddit.display_name 我有两个函数必须这样做,这真的很难看。有没有

我正在使用praw模块,我发现我的对象有时有一个属性
subreddit
,它有时是一个字符串,有时是一个具有自己属性的对象。我用以下方法处理了它:

for c in comments:
    if isinstance(c.subreddit, str):
        subreddit_name = c.subreddit
    else:
        subreddit_name =  c.subreddit.display_name
我有两个函数必须这样做,这真的很难看。有没有更好的方法来处理这个问题?

我宁愿使用,而不是:

您也可以尝试使用默认值,如
dict.get

subreddit_name = getattr(c.subreddit, 'display_name', c.subreddit)
这实际上是一个更简洁的版本:

subreddit_name = (c.subreddit.display_name 
                  if hasattr(c.subreddit, 'display_name') 
                  else c.subreddit)
我宁愿使用而不是:

您也可以尝试使用默认值,如
dict.get

subreddit_name = getattr(c.subreddit, 'display_name', c.subreddit)
这实际上是一个更简洁的版本:

subreddit_name = (c.subreddit.display_name 
                  if hasattr(c.subreddit, 'display_name') 
                  else c.subreddit)

我将尝试getattr,不知道您可以提供默认值。谢谢你的首字母缩写。我会试试getattr,不知道你可以提供默认值。谢谢你的首字母缩略词。