如果是用户输入,则找不到对象
Object not found if its a user input
search_type = str(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): "))
hot_apex = subred.search_type(limit=num)
我希望 search_type 来自用户输入,这样用户可以写 top 然后搜索 type = top
并更改为
hot_apex = subred.top(limit=num)
但是,我收到此错误消息 'Subreddit' object has no attribute 'search_type' however top is a object of subreddit
只需使用条件语句:
search_type = str(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): "))
if search_type == "top"
hot_apex = subred.top(limit=num)
elif search_type == "hot":
hot_apex = subred.hot(limit=num)
else:
#return error
search_type
是定义为字符串的变量。
subred.search_type
尝试在 subred
对象中查找名为 "search_type"
的 属性 。它不解析变量 search_type
并查找由该变量的值命名的属性。为此,您需要使用 getattr()
函数。
search_type = input("Enter type: ")
try:
func_to_call = getattr(subred, search_type)
results = func_to_call(limit=num)
except AttributeError:
print("Invalid input")
results = []
或者,您可以使用 if..elif
阶梯,但是如果您有许多可能的有效输入,这很快就会变得很麻烦:
if search_type == "hot":
results = subred.hot(limit=num)
elif search_type == "top":
results = subred.top(limit=num)
else:
print("Invalid input")
results = []
search_type = str(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): "))
hot_apex = subred.search_type(limit=num)
我希望 search_type 来自用户输入,这样用户可以写 top 然后搜索 type = top 并更改为
hot_apex = subred.top(limit=num)
但是,我收到此错误消息 'Subreddit' object has no attribute 'search_type' however top is a object of subreddit
只需使用条件语句:
search_type = str(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): "))
if search_type == "top"
hot_apex = subred.top(limit=num)
elif search_type == "hot":
hot_apex = subred.hot(limit=num)
else:
#return error
search_type
是定义为字符串的变量。
subred.search_type
尝试在 subred
对象中查找名为 "search_type"
的 属性 。它不解析变量 search_type
并查找由该变量的值命名的属性。为此,您需要使用 getattr()
函数。
search_type = input("Enter type: ")
try:
func_to_call = getattr(subred, search_type)
results = func_to_call(limit=num)
except AttributeError:
print("Invalid input")
results = []
或者,您可以使用 if..elif
阶梯,但是如果您有许多可能的有效输入,这很快就会变得很麻烦:
if search_type == "hot":
results = subred.hot(limit=num)
elif search_type == "top":
results = subred.top(limit=num)
else:
print("Invalid input")
results = []