您的位置:首页技术文章
文章详情页

python错误 __str__() Takes 0 positional arguments but 1 was given

浏览:51日期:2022-06-28 11:53:51

问题描述

# -*- coding:gb2312 -*-class car: # 属性# 方法 def __str__():print('哈哈哈哈哈哈啊哈')def move():print('车在移动。') def Whistle():print('车载鸣笛。')BMW = car()print(BMW)

提示错误:

python错误  __str__() Takes 0 positional arguments but 1 was given

google翻译了一下,说是取0个位置参数,但给出1不太理解这个什么意思。

问题解答

回答1:

在class里面定义的函数, 都需要提供一个self的位置参数, 因为在类实例化时, 会传入实例对象, 进而和函数进行绑定, 所以代码应该调整为:

# -*- coding:gb2312 -*-class car: # 属性 # 方法 def __str__(self):return ('哈哈哈哈哈哈啊哈') def move(self):print('车在移动。') def Whistle(self):print('车载鸣笛。')BMW = car()print(BMW)

对于 method 和 function的关系可以参考我的文章: Python: 函数与方法的区别

标签: Python 编程
相关文章: