Python error: NameError: name 'new' is not defined

Asked 2 years ago, Updated 2 years ago, 39 views

class S(Car):



    def __init__(self,type_=""):
        self.maxfuel = 60
        self.fueleconomy = 10

        if (type_ == new):
            self.type_ = new
        elif (type_ == old):
            self.type_ = old
        else:
            print("Choose only one of the new and old".")

I wrote the code like this and said s1=S(new) but NameError: name 'new' is not defined appears. How do I redefine new?

python error

2022-09-20 16:00

2 Answers

It seems to be a problem caused by not specifying what new and old are.

If you specify the initial type as a bonus, you can reduce the if statement by one.

class S(Car):
    def __init__(self, type_ = 'new'):
        self.maxfuel = 60
        self.fueleconomy = 10
        self.type_ = 'new'

        if (type_ == 'old'):
            self.type_ = 'old'


2022-09-20 16:00

If you only check with the code you posted, as the beginner said,

The problem is caused by not specifying what new old is.

And I think the part where the error occurred as shown in the comment below is not reflected in this question.

I think you'd better check it out again.

class Car:
    def __init__(self):
        self.test = ''

class S(Car):
    def __init__(self, type_=""):
        self.maxfuel = 60
        self.fueleconomy = 10

        if (type_ == "new"):
            self.type_ = "new"
        elif (type_ == "old"):
            self.type_ = "old"
        else:
            print("Choose only one of the new and old".")

    def __str__(self):
        return f'{self.maxfuel} , {self.fueleconomy} , {self.type_}'

try:
    s = S("new")
    print(s) #60 , 10 , new

    s1 = Car("") #error
except Exception as e:
    print(e) #__init__() takes 1 positional argument but 2 were given


2022-09-20 16:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.