【问题标题】:Python 3: Type Error Object.__new__() takes no parametersPython 3:类型错误 Object.__new__() 不带参数
【发布时间】:2015-01-15 02:16:23
【问题描述】:

我在开始上课时遇到了问题。我收到此类型错误,但我不确定是什么原因造成的。我检查了其他问题,但他们的答案似乎不能解决我的问题。

#create the car class
class Car:

    #create the initiator function
    def __init__carStats(self, year, model):
        self.__speed = 0
        self.__year = year
        self.__model = model

    def setModel(self, model):
        self.__model = model

    def setYear(self, year):
        self.__year = year

    #create speed increase function
    def speedUp(self):
        print('Calling speed up function.')
        self.__speed += 5

    #create slowdown function
    def slowDown(self):
        print('Calling slow down function.')
        self.__speed -= 5

    #create show speed function
    def showSpeed(self):
        print('The', self.__year, self.__model, '\'s current speed is', self.__speed,'miles per houer')

#create main function
def Main():
    year = ''
    make = ''
    #get car year and make
    make = input('What model is the car? \n')
    year = input('What year is the car?" \n')

    myCar = Car(year, make)

Main()

【问题讨论】:

    标签: class python-3.x typeerror


    【解决方案1】:

    必须调用 Python 类的“构造函数”__init__,默认的 __init__ 不带参数,因此会出现类型错误。 将您的初始化更改为:

    def __init__(self, year, model):
    

    没有办法重载__init__,但您可以使用带有默认值的命名参数,这样它们就可以被省略。

    def __init__(self, year=None, model=None):
    

    What is a clean, pythonic way to have multiple constructors in Python?

    【讨论】:

    • 这确实有效,非常感谢您,对于迟到的回复感到抱歉。
    猜你喜欢
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 2016-04-03
    • 2013-06-09
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多