selfteaching / selfteaching/selfteaching-python-camp

Day12 关于作业中涉及的装饰器和自定义函数问题

Open
#1,585 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
151
Forks
875
PR merge metrics
No merged PRs in 30d

Description

今天作业要求是对全体好友自动回复,我最初自己实现的功能只能针对特定好友。后来看了1期徐悦学长的方法,他使用了一个函数装饰器@bot.register(my_friend,SHARING),并定义了一个auto_reply(msg)函数。经分析,装饰器的作用是监听来自my_friend的消息,如果类型为SHARING(分享内容),即把消息内容赋值给msg变量。只是我不理解的是,函数返回的结果将直接自动回复给发送消息的好友(my_friend),这应该就是auto_reply这个函数的作用,但为什么这明明是个自己定义的函数,却能自带自动回复的功能?经过搜索,网上有介绍该库自动回复的方法,貌似auto_reply(msg)只要括号里的参数是msg,就自带将函数return的结果自动回复的功能,无论函数名称为什么。这应该是这个库的自带功能。
以上我的理解正确吗?请高手解惑,谢谢!

附上徐悦的作业:

from mymodule import stats_word as sw
import requests
from pyquery import PyQuery
from wxpy import *

bot = Bot() #扫码登录微信

my_friend = bot.friends() #定义好友变量

@bot.register(my_friend,SHARING) #接收share类信息
def auto_reply(msg):
    msg_from_friend = requests.get(msg.url) 
    document = PyQuery(msg_from_friend.text)
    content = document('#js_content').text()
    #URL信息提取
    reply = sw.stats_text(content,count=100)
    return reply #将词频自动发给好友

embed() #保持监听状态

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the supplied Python example, especially the @bot.register(my_friend, SHARING) decorator and auto_reply(msg) callback, then read wxpy's registration and callback documentation. Confirm how the callback parameter and return value are handled, and document the behavior clearly for this example.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.