__str__ 函数在 Pycharm 和 Vim 编辑器中表现不同
__str__ function behaving differently in Pycharm and Vim editor
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__
方法中进行修改,但 return 语句在 vim
中不起作用
Python f 弦仅在 Python 3.6 中引入,因此如果您使用的是 Python 3.5,它们将无法工作。
3.6 之前 Python 中的等效功能是 format()
方法。
所以代替:
return f'point : ({self.x}, {self.y}, {self.z})'
您可以使用:
return 'point : ({self.x}, {self.y}, {self.z})'.format(self=self)
如果你想兼容 Python 3.5 或更低版本。
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__
方法中进行修改,但 return 语句在 vim
Python f 弦仅在 Python 3.6 中引入,因此如果您使用的是 Python 3.5,它们将无法工作。
3.6 之前 Python 中的等效功能是 format()
方法。
所以代替:
return f'point : ({self.x}, {self.y}, {self.z})'
您可以使用:
return 'point : ({self.x}, {self.y}, {self.z})'.format(self=self)
如果你想兼容 Python 3.5 或更低版本。