1

WHen I execute, it throws the error:

 ....
  ......
    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

please help

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()
kederrac
  • 16,819
  • 6
  • 32
  • 55
Roy
  • 45
  • 1
  • 7

3 Answers3

0

Class attributes are simply added to the class - not prefixed by the class name:

class Dog(Pet):
    numberoflegs = 4
    # etc

class Fish(Pet):
    numberoflegs = 0

You can change it using Dog.numberoflegs = 3 (if you have 3-legged dogs by default).

Classattributes are shared between all instances.

See

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Thank you so much for taking the time for such a detailed explanation! :) I just started to learn web application development using python 3.7. could you recommend some better tutorial as the one I am currently following, has such issues as you noticed. – Roy Apr 14 '20 at 08:03
  • I just tried to run my above code using separate files for each animal, inheriting the animal super class within the same project directory. now it doesn't throw any exception. But no output is shown what I was expecting by running the mian.py containing `kuta = Dog() kuta.countlegs() kuta.bark() machi = Fish() machi.countlegs()` – Roy Apr 14 '20 at 08:19
  • 1
    @kederr The -1 answer has the internal link for the +130 / +145 rated duplicate in it. But youre ofcourse correct - change the link to be direct instead of indirect – Patrick Artner Apr 14 '20 at 08:45
0

you can define your class Dog in this way:

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

your class attribute numberoflegs do not need Dog.

you are getting the error because you are trying to use the class at "creation" time, before to even have the Dog class

kederrac
  • 16,819
  • 6
  • 32
  • 55
0

Change:

class Dog(Pet):
    Dog.numberoflegs = 4

to:

class Dog(Pet):
    numberoflegs = 4

It already has the scope of the class, and you can't refer to the class by name yet since it's still being defined.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41