You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PRAW中用户输入作Subreddit方法名报无search_type属性错误

PRAW 动态调用Subreddit方法问题解决

报错原因

subred.search_type 这种写法是将 search_type 作为固定属性名直接访问,Python不会自动解析变量内部存储的字符串值(比如用户输入的"top")去匹配对应方法,因此会抛出 'Subreddit' object has no attribute 'search_type' 的错误。

实现方案

使用Python内置的 getattr() 函数动态获取对象的方法,该函数接收3个参数:对象、要获取的属性/方法名字符串、属性不存在时的默认返回值,完全匹配你的需求。

基础可用代码

# 读取用户输入并去除首尾多余空格
search_type = input("Enter search paramiter. (type top for top of all time) (type hot for populour posts in the last 24 hours) (type new for the newest posts): ").strip()
# 定义你需要的返回帖子数量
num = 25
# 动态获取对应方法,不存在时返回None
target_method = getattr(subred, search_type, None)
# 校验获取到的对象是否可被调用
if not callable(target_method):
    print("输入的搜索类型无效,请检查后重试")
else:
    # 调用方法传入limit参数,等价于直接写 subred.top(limit=num) 这类写法
    hot_apex = target_method(limit=num)

注意:getattr 返回的是方法对象,不是执行后的结果,必须加括号传入参数才会实际获取帖子数据。

安全优化:加白名单限制

直接使用用户输入作为方法名存在风险——用户如果输入了Subreddit对象的其他危险方法名(比如修改、删除内容的接口),会引发误操作。建议提前限定允许调用的方法范围,同时兼容大小写输入:

# 预定义允许调用的方法白名单
ALLOWED_SEARCH_TYPES = {"top", "hot", "new"}
search_type = input("Enter search paramiter. (type top for top of all time) (type hot for populour posts in the last 24 hours) (type new for the newest posts): ").strip().lower()
# 校验输入合法性
if search_type not in ALLOWED_SEARCH_TYPES:
    print("输入的搜索类型不合法,仅支持top/hot/new三种类型")
else:
    target_method = getattr(subred, search_type)
    hot_apex = target_method(limit=num)

内容的提问来源于stack exchange,提问作者Lewis Revel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 16:06:03