search

Home  >  Q&A  >  body text

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

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

BMW = car()

print(BMW)

Error message:

Google translated it and said that it takes 0 position parameters, but it gave 1
I don’t understand what this means.

扔个三星炸死你扔个三星炸死你2724 days ago1945

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-06-15 09:24:17

    The functions defined in class need to provide a positional parameter of self, because when the class is instantiated, the instance object will be passed in and then bound to the function, so the code should be adjusted to:

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

    For the relationship between method and function, you can refer to my article: Python: The difference between functions and methods

    reply
    0
  • Cancelreply