【问题标题】:when define function in the class how to get the arguments? [duplicate]在类中定义函数时如何获取参数? [复制]
【发布时间】:2020-02-25 23:35:10
【问题描述】:

我想向类中的函数发送参数,但出现以下错误 我应该如何定义一个可以使用参数的函数?

   class Tistory:
        def __init__(self, m_client_id, m_redirect_uri, m_user_id, m_password, m_blogname):
            self.m_client_id = m_client_id
            self.m_redirect_uri = m_redirect_uri
            self.m_user_id = m_user_id
            self.m_password = m_password
            self.m_blogname = m_blogname

    def wrtiePost(m_title, m_content, m_category, m_tag):
        params = {
            'blogName' : self.m_blogname,
            'title' : m_title,
            'content' : m_content,
            'tag' : m_tag,
            'category' : m_category,
            'visibility' : '0',
            #'published' : '',
            #'slogan' : '',
            #'acceptComment' : '1',
            #'password' : '',
            'access_token' : self.getAccessToken(),
            'output' : 'json'
        }
        ....

if __name__== "__main__":
    tistory = Tistory(g_client_id,g_redirect_uri,g_user_id,g_password, g_blogname)
    #tistory.getAccessToken()
    tistory.writePost(m_title="test",m_content="test",m_category="test", m_tag="test")

当我在类中调用函数时为什么会出现以下错误?

Traceback (most recent call last):
  File "/Users/chullee/github/tistory/class/tistory.py", line 113, in <module>
    tistory.writePost(m_title="test",m_content="test",m_category="test", m_tag="test")
TypeError: writePost() got an unexpected keyword argument 'm_title'

【问题讨论】:

  • 您需要在任何类方法上接受self。否则,第一个参数变为self
  • ...也就是说,问题中的代码实际上并没有重现问题,因为它的缩进是错误的。
  • 我已经添加了 self 但还是不行
  • 嗯,是的——仅仅因为你解决了一个问题并不意味着你没有更多的问题。然而,在与他们交谈之前,我们需要先了解其他问题,而且每个 Stack Overflow 问题都应该只涉及一个问题。

标签: python


【解决方案1】:

Python 自动将类的实例作为第一个参数传递给成员方法。我们通常将此参数称为self。所以把你的def改成这样:

    def writePost(self, m_title, m_content, m_category, m_tag):

【讨论】:

  • 文件 "/Users/chullee/github/tistory/class/tistory.py",第 111 行,在 tistory.writePost("test","test","test"," test") TypeError: writePost() 接受 0 个位置参数,但给出了 5 个
  • def wrtiePost(self, m_title, m_content, m_category, m_tag): print("开始 writePost")
  • @ChulLee 您问题中的代码不会给出该错误。请提供一个minimal reproducible example,我们调用它可以运行并得到您所询问的相同错误。
  • @ChulLee 首先,检查您的拼写。 wrtiePost()writePost() 不同。其次,检查问题中代码中的缩进是否与实际代码中的缩进相同。 class Tistory: 似乎缩进太远,我不确定你对 def writePost() 的缩进是什么意思。
  • @ChulLee 如果您仍需要帮助,请使用您最新版本的代码发布一个新问题。
猜你喜欢
  • 1970-01-01
  • 2014-07-03
  • 1970-01-01
  • 2018-04-12
  • 1970-01-01
  • 2020-08-22
  • 1970-01-01
  • 2014-05-31
  • 2019-01-21
相关资源
最近更新 更多