1

Я учу python, в данный момент классы. Написав простую программу (на 90% списанную с учебника), компилятор выдаёт следующую ошибку: NameError: name 'Dog' is not defined. Как её исправить?

class Dog:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def bark(self):
        print("woof!")

    toby = Dog ("toby", "brown")        
    print("This is ", toby.name,".")
    print("It's", toby.color)
    bark()  

class Cat:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def meow(self):
        print("meow")   
    felix = Cat ("felix", "white")
    print("This is ", felix.name, ".")
    print("It's", felix.color)
    meow()

1 ответ 1

4

В Python важно строго соблюдать отступы.

Я думаю, вы имеете в виду следующий код

class Dog:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def bark(self):
        print("woof!")

toby = Dog ("toby", "brown")        
print("This is ", toby.name,".")
print("It's", toby.color)
bark()  

class Cat:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def meow(self):
        print("meow")

felix = Cat ("felix", "white")
print("This is ", felix.name, ".")
print("It's", felix.color)
meow()

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.