【问题标题】:__str__ function behaving differently in Pycharm and Vim editor__str__ 函数在 Pycharm 和 Vim 编辑器中的行为不同
【发布时间】:2020-07-12 19:34:46
【问题描述】:
class Point:
      def __init__(self, x, y, z):
            self.x = x
            self.y = y
            self.z = z
      def __str__(self):
            return f'point : ({self.x}, {self.y}, {self.z})' #works perfectly in pycharm but shows syntax error in vim
            return 'point' + ':' + '(' + self.x + ',' + self.y + ',' + self.z + ')' # shows error that cannot convert int to string implicitly

p1 = Point(4, 2, 9)
print(p1)

我想要的输出格式应该是point : (4, 2, 9)

__str__ 方法中进行修改,但返回语句在 vim 中不起作用

【问题讨论】:

    标签: python-3.x python-3.5


    【解决方案1】:

    Python f-strings 仅在 Python 3.6 中引入,因此如果您使用的是 Python 3.5,它们将无法工作。

    Python 3.6 之前的等效功能是format() 方法。

    所以而不是:

    return f'point : ({self.x}, {self.y}, {self.z})'
    

    你可以使用:

    return 'point : ({self.x}, {self.y}, {self.z})'.format(self=self)
    

    如果你想兼容 Python 3.5 或更低版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      • 2015-05-23
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      相关资源
      最近更新 更多