【问题标题】:Customize def __str__(self): method when creating a class in Python自定义 def __str__(self): 在 Python 中创建类时的方法
【发布时间】:2021-10-16 19:36:08
【问题描述】:

我在 Python3 中创建了一个 MultipleChoice 类,其中第一个参数应该是一个问题,第二个参数是一个带有备选方案的列表(每个条目都是一个字符串,没有编号),第三个参数是正确的数字回答。包含备选方案的列表可能有不同的长度。

我已经创建了这个类,并且我正在尝试创建一个 _str_ 方法来返回问题和问题下的所有备选方案,但这次是编号的。我想要实现的目标如下所示:

question1 = MultipleChoice('What´s best?', ['Mac', 'PC'], 1)
question2 = MultipleChoice('Biggest city in England?' , ['Manchester','Liverpool', 'London'], 3)
print(question1)
print(question2)

预期输出:

什么是最好的? 1 - 麦克 , 2 - 个人计算机

英格兰最大的城市? 1 - 曼彻斯特 , 2 - 利物浦 , 3 - 伦敦

我尝试在 _str_ 方法的 f 字符串中的括号中插入方法,但未成功。我这样做是因为我假设我必须用备选方案遍历列表并为每个条目分配一个类似于索引号的数字,并且认为像这样的更复杂的任务最好在单独的方法中完成(而不是尝试这样做在 f 字符串的括号内。

这也是一项学校作业,所以我必须使用 _str_ 方法来实现。

任何帮助将不胜感激。以下是我目前的代码:

class MultipleChoice:
    #Constructor
    def __init__(self, question, alternatives, correct_answer):
        self.question = question
        self.alternatives = alternatives
        self.correct_answer = correct_answer
        
    def __str__(self):
        return f'{self.question}? \n{self.alternatives}.'
       
    
if __name__ == '__main__':
    question1 = MultipleChoice('What´s best?', ['Mac', 'PC'], 1)
    question2 = MultipleChoice('Biggest city in England?' , ['Manchester','Liverpool', 'London'], 3)
    print(question1)
    print(question2)

【问题讨论】:

    标签: python-3.x class methods printf


    【解决方案1】:

    为此,我们可以使用enumerate 轻松获取列表中给定元素的索引号,并使用它的第二个参数将其从1开始,我们可以使用它来获取

    >>> question = 'Biggest city in England?'
    >>> alternatives = ['Manchester', 'Liverpool', 'London']
    >>> for i,v in enumerate(alternatives,1):
            print(f'{i} - {v}')
    
        
    1 - Manchester
    2 - Liverpool
    3 - London
    >>>     
    

    现在让我们把之前的循环改成合适的list comprehension

    >>> [f'{i} - {v}' for i,v in enumerate(alternatives,1)]
    ['1 - Manchester', '2 - Liverpool', '3 - London']
    >>>
    

    现在我们使用str.join 将它们连接在一起并删除 [] 以使其成为generator expression,而我们正在使用它

    >>> temp=', '.join(f'{i} - {v}' for i,v in enumerate(alternatives,1))
    >>> temp
    '1 - Manchester, 2 - Liverpool, 3 - London'
    >>> 
    

    现在我们已经完成了 80%,让我们进行最后的润色

    >>> f"{question} {temp}"
    'Biggest city in England? 1 - Manchester, 2 - Liverpool, 3 - London'
    >>> 
    

    我们完成了。

    f-string 也可以接受几乎任何 python 表达式,所以我们可以把它变成一个单行

    >>> f"{question} { ', '.join(f'{i} - {v}' for i,v in enumerate(alternatives,1)) }"
    'Biggest city in England? 1 - Manchester, 2 - Liverpool, 3 - London'
    >>>      
    

    【讨论】:

      【解决方案2】:

      您可以尝试使用__str__,如下所示(使用破折号和/或空格而不是换行符更新 f 字符串以满足您的需求):

      >>> class MultipleChoice:
      ...     #Constructor
      ...     def __init__(self, question, alternatives, correct_answer):
      ...         self.question = question
      ...         self.alternatives = alternatives
      ...         self.correct_answer = correct_answer
      ...     def __str__(self):
      ...         return f'{self.question}\n' + '\n'.join(f'{i} {a}' for i, a in enumerate(self.alternatives,1))
      ... 
      >>> question1 = MultipleChoice('What´s best?', ['Mac', 'PC'], 1)
      >>> question2 = MultipleChoice('Biggest city in England?' , ['Manchester','Liverpool', 'London'], 3)
      >>> 
      >>> print(question1)
      What´s best?
      1 Mac
      2 PC
      >>> print(question2)
      Biggest city in England?
      1 Manchester
      2 Liverpool
      3 London
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-12
        • 1970-01-01
        • 2022-01-13
        • 1970-01-01
        • 2017-07-28
        • 2010-10-15
        • 1970-01-01
        相关资源
        最近更新 更多