簡體   English   中英

為什么我在運行 class 程序時收到此 NameError?

[英]Why I am getting this NameError while running my class program?

class Animal: 

    def __init__(self,name):
        self.name=name

    def sound(self):
        return 'this is animal sound'

    class Dog(Animal):
        def __init__(self,name, breed):
            super().__init__(name)
            self.breed=breed

    class Cat(Animal):
        def __init__(self,name,breed):
            super().__init__(name)
            self.breed=breed

doggy=Dog('Tomy','pug')
print(doggy.sound())

它顯示了以下錯誤:

----------
Traceback (most recent call last):
  File "exception_handlin_2.py", line 1, in <module>
    class Animal:
  File "exception_handlin_2.py", line 9, in Animal
    class Dog(Animal):
NameError: name 'Animal' is not defined

縮進。 DogCat的 class 定義應低 1 個縮進。

class Animal: 

    def __init__(self,name):
        self.name=name

    def sound(self):
        return 'this is animal sound'

class Dog(Animal):
    def __init__(self,name, breed):
        super().__init__(name)
        self.breed=breed

class Cat(Animal):
    def __init__(self,name,breed):
        super().__init__(name)
        self.breed=breed

doggy=Dog('Tomy','pug')
print(doggy.sound())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM