【问题标题】:Python Class() takes no argument error. I am using Self [closed]Python Class() 没有参数错误。我正在使用自我 [关闭]
【发布时间】:2019-01-31 21:01:39
【问题描述】:

我一直在浏览 Stack 和整个互联网,但我无法找到我正在处理的问题。我是 Python 新手,我正在学习类的工作原理。我编写了一个非常简单的类和函数来将它打印到控制台。


class Car():

    def __intit__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def get_descriptive_name(self):
        long_name = str(self.year), + " " + self.make + " " + self.model
        return long_name.title()

my_new_car = Car('Chevy', 'sonic', 2015)

print(my_new_car.get_descriptive_name())

但是当我运行编译器时,它返回错误 Car() 没有参数。我知道需要 self 参数,并且我已经将它们包含在我能想到的所有区域中。我已经做了很多实验,但我没有尝试改变它。我希望有人可以向我解释这一点,或者可能知道相关主题?

提前感谢您的帮助!

【问题讨论】:

  • 你拼错了__init__()(你目前有__intit__())。
  • 拼错__init__
  • 为了记录,这个问题是完全可以重现的。我有同样的错误,这是谷歌的第一个堆栈溢出答案。为我节省了大量时间。公平地说,虽然我错过了第二个 I 而不是添加一个额外的 t。谢谢你的问题!!!

标签: python class compiler-errors


【解决方案1】:

您没有采用实例参数的__init__ 方法,因为您将其拼写为def __intit__(self, make, model, year):。因此,在实例化 my_new_car = Car('Chevy', 'sonic', 2015) 时,您将参数传递给 Car 并不期望它们

【讨论】:

  • 我要去打自己一巴掌了。
  • 添加了 int 而不是 init。我的坏
【解决方案2】:

简单的错字:

def __intit__(self, make, model, year):

应该是__init__

【讨论】:

  • 老实说,我不确定我是怎么错过的,我确信我的参数有问题。
【解决方案3】:
class Car():

    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def get_descriptive_name(self):
        long_name = str(self.year) + " " + self.make + " " + self.model
        return long_name.title()

my_new_car = Car('Chevy', 'sonic', 2015)

print(my_new_car.get_descriptive_name())

You have two errors, 
1) def __init__ (like above)
2) long_name = str(self.year) + " " + self.make + " " + self.model
after str(self.year) you have unnecessary commas

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-09
    • 2021-05-10
    • 2022-06-15
    • 1970-01-01
    • 2015-06-10
    • 2016-04-02
    • 1970-01-01
    • 2022-10-15
    相关资源
    最近更新 更多