首页 > 解决方案 > Python 程序将 self 计为参数,并且 a 导致 TypeError

问题描述

class Shirt:

    def __init__(self, shirt_color, shirt_size, shirt_style, shirt_price):
        self.color = shirt_color
        self.size = shirt_size
        self.style = shirt_style
        self.price = shirt_price

    def change_price(self, new_price):
        self.price = new_price

    def discount(self, discount):
        return self.price * (1 - discount)

from shirt import Shirt

shirt_one = Shirt('red', 'M', 'long-sleeved, 45')
shirt_two = Shirt('orange', 'S', 'short-sleeved, 30')

print(shirt_one.price)
print(shirt_two.color)

shirt_two.change_price(45)
print(shirt_two.price)
TypeError: __init__() 正好需要 5 个参数(给定 4 个)

标签: python

解决方案


shirt_one = Shirt('red', 'M', 'long-sleeved, 45')
shirt_two = Shirt('orange', 'S', 'short-sleeved, 30')

应该是

shirt_one = Shirt('red', 'M', 'long-sleeved', '45')
shirt_two = Shirt('orange', 'S', 'short-sleeved', '30')

您期待 4 个参数(如果包含,则为 5 个)

def __init__(self, shirt_color, shirt_size, shirt_style, shirt_price):

但你传递了 3 个参数。


推荐阅读