【问题标题】:How to apply python methods within a Class?如何在一个类中应用 python 方法?
【发布时间】:2015-03-02 14:41:27
【问题描述】:

如何在类中使用“默认”方法,例如:string.lower()?

这是我得到的错误:

result = text.lower.replace(string.punctuation, ' ').split(' ')
AttributeError: MyClass instance has no attribute 'lower'

【问题讨论】:

    标签: python class python-2.7 python-3.x attributeerror


    【解决方案1】:

    你又少了一组()

    result = text.lower().replace(string.punctuation, ' ').split(' ')
                       ^
    

    【讨论】:

    • 我添加了大括号,但仍然出现错误。结果 = text.lower().replace(string.punctuation, ' ').split(' ') AttributeError: MyClass instance has no attribute 'lower'
    • 什么是text?是str 吗?你能把你的电话显示给isWordIn吗?
    • 文本是一个类似于新闻标题的字符串'Koala bears are soft and cuddly'-class TitleTrigger(WordTrigger): def evaluate(self, text): return(self.isWordIn(text))
    • @Omicron 您没有添加(),否则您不会收到错误“...没有属性 'lower'”。它会说明没有正确的方法。
    • 同时编辑您的原始帖子会使下面的答案无效,即使这正是您的问题的根源。
    【解决方案2】:

    lower 方法中缺少()。

    a.lower 将返回函数对象。

    例如

    >>> a = "ABCf"
    >>> a.lower
    <built-in method lower of str object at 0xb7047ac0>
    >>> a.lower()
    'abcf'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-11
      • 2023-01-18
      • 2021-01-29
      • 1970-01-01
      • 2014-11-07
      • 2011-07-03
      相关资源
      最近更新 更多