python - Python如果对象具有属性
问题描述
我浏览了一些答案,但找不到我正在寻找的确切内容。如果有我可能错过的答案,我很乐意看看它。
我得到一个analytics
对象(分析是对象的名称)。它是根据谷歌分析数据构建的。这个想法是我可以从这个对象中提取某个报告get_UserData
(使用 user_id)并使用该数据来完成我的程序。
我遇到的问题是我必须遍历 1200 个用户并检查每个用户是否有数据(换句话说,我有一长串可能的用户,但只有一些人是活跃的,只有那些活跃的人在目的)
完成此过程最多可能需要 15 分钟,我想避免不得不拉,get_UserData
因为它需要更长的时间。我的计划是绕过get_UserData
如果用户没有数据analytics
以节省时间
我希望这是有道理的(本质上:我想节省时间,并且是面向对象编程的新手)
我拥有的代码:
def initialise_analytics_reporting():
"""Initializes the analytics reporting service object.
Returns:
an authorized analytics reporting service object.
"""
# Parse command-line arguments.
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[tools.argparser])
flags = parser.parse_args([])
# Set up a Flow object to be used if we need to authenticate.
flow = client.flow_from_clientsecrets(
"ga-credentials/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.com.json",
scope='https://www.googleapis.com/auth/analytics.readonly',
message=tools.message_if_missing(client_secrets_path))
# Prepare credentials, and authorize HTTP object with them.
# If the credentials don't exist or are invalid run through the native client
# flow. The Storage object will ensure that if successful the good
# credentials will get written back to a file.
storage = file.Storage('ga-credentials/analyticsreporting.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(http=httplib2.Http())
# Build the service object.
analytics = build('analyticsreporting', 'v4', http=http)
return analytics
def get_user_Activity(analytics, VIEW_ID, user_id, time):
"""
:type user_id: str
"""
# Use the Analytics Service Object to query the Analytics Reporting API V4.
try:
if hasattr(analytics.userActivity(), user_id): <<<<----- THIS IS WHAT I HAVE DONE
x = analytics.userActivity().search(
body={
"viewId": VIEW_ID,
"user": {
"type": "USER_ID",
"userId": user_id
},
"dateRange": {
"startDate": time,
"endDate": "yesterday"
},
"activityTypes": [
"PAGEVIEW", "EVENT"
]
}
).execute()
except:
pass
return x
但是在运行这个时,我没有从活跃的用户那里得到任何数据?
请帮忙。
解决方案
hasattr
函数假设第二个参数是您测试的属性的名称,而不是属性的值。例如,user_id='id'
只有在userActivity
具有属性 id ( userActivity.id
) 时测试才会成功。
推荐阅读
- r - choroplethrZip 返回“无法添加绑定”字幕错误 - 即使使用示例代码
- javascript - 关键帧背景图像动画不使用预加载图像
- ruby - 在 ruby 中将数据写入 csv 文件的问题
- python - 为 Keras 中的某些张量元素分配新值
- r - 累积对数正态函数不返回正确的概率
- c# - 发送到 Azure 事件中心错误
- javascript - 错误无限滚动Javascript,向上滚动时不加载
- python - 安装和使用 RPy2(使用 conda),以便它使用 /usr/lib/RR 中的默认 R 安装
- python - Python 数据科学库 vs SQL
- dart - 如何禁用 Flutter 的 Navigator 类的返回操作