【问题标题】:Error is thrown while practicing Inheritance in Python 3在 Python 3 中练习继承时抛出错误
【发布时间】:2020-04-14 07:44:36
【问题描述】:

当我执行时,它会抛出错误:

 ....
  ......
    class Dog(Pet):
  File "D:\untitled2\Pet.py", line 13, in Dog
    Dog.numberoflegs = 4
NameError: name 'Dog' is not defined
Fish.numberoflegs = 0
NameError: name 'Fish' is not defined

请帮忙

class Pet:
    numberoflegs = 0
    def sleep(self,name):
        print("the {} sleeps".format(name))
    def countlegs(self):
        print("I have {} legs".format(self.numberoflegs))


#type = input("enter pet type")
#dog.sleep(type)

class Dog(Pet):
    Dog.numberoflegs = 4
    def bark(self):
        print ("the dog sounds woof")

class Fish(Pet):
    Fish.numberoflegs = 0


kuta = Dog()
kuta.countlegs()
kuta.bark()
machi = Fish()
machi.countlegs()

【问题讨论】:

    标签: python inheritance parent-child


    【解决方案1】:

    类属性只是简单地添加到类中——不以类名为前缀:

    class Dog(Pet):
        numberoflegs = 4
        # etc
    
    class Fish(Pet):
        numberoflegs = 0
    

    您可以使用Dog.numberoflegs = 3 更改它(如果您默认有三足狗)。

    类属性在所有实例之间共享。

    【讨论】:

    • 非常感谢您抽出宝贵时间进行如此详细的解释! :) 我刚开始学习使用 python 3.7 进行 Web 应用程序开发。你能推荐一些更好的教程,就像我目前正在关注的那样,有你注意到的问题。
    • 我只是尝试为每个动物使用单独的文件运行我的上述代码,在同一项目目录中继承动物超类。现在它不会抛出任何异常。但是通过运行包含 kuta = Dog() kuta.countlegs() kuta.bark() machi = Fish() machi.countlegs() 的 mian.py 没有显示我所期望的输出
    • @kederr -1 答案包含 +130 / +145 评级副本的内部链接。但你当然是正确的 - 将链接更改为直接而不是间接
    【解决方案2】:

    变化:

    class Dog(Pet):
        Dog.numberoflegs = 4
    

    到:

    class Dog(Pet):
        numberoflegs = 4
    

    它已经有了类的作用域,你还不能通过名字来引用这个类,因为它还在被定义中。

    【讨论】:

      【解决方案3】:

      你可以这样定义你的类Dog

      class Dog(Pet):
          numberoflegs = 4
          def bark(self):
              print ("the dog sounds woof")
      

      你的类属性numberoflegs不需要Dog.

      您收到错误是因为您试图在“创建”时使用该类,甚至在拥有 Dog 类之前

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-29
        • 2016-03-06
        • 1970-01-01
        • 2014-07-01
        相关资源
        最近更新 更多