Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NameError: name ' ' is not defined, python

I have to create a class with two methods. This is the exercise:

enter image description here

This is my attempted code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Cats():
    
     def __init__(self, name, breed, size):
         self.name = name
         self.breed = breed
         self.size = size
        
     def friends(self, cat2):
         print(self.name, 'and', cat2.name, 'are friends')
        
     def fight(cat1, cat2):
         if cat1.size == 'Big' and cat2.size == 'Small':
             print(cat1.name, 'Win the fight')
         elif cat2.size == 'Big' and cat1.size == 'Small':
             print(cat2.name, 'Win the fight')
         else:
             print('There is no fight, they are friends')

Let’s suppose:

cat1 = Cats('Tommy','breedx','Big')
cat2 = Cats('Garfield','breedy','Small')

fight(cat1,cat2)

The expected output would be:

Tommy Win the fight

The output I receive:

enter image description here

Could someone suggest me what is the correct way to do my code? I’m a bit confused.

>Solution :

The fight function is defined inside the Cat class so you can’t just access it globally without an object reference of type Cat.

If you want the function to remain inside the Cat class, you can change it to:

def fight(self, cat2):
     if self.size == 'Big' and cat2.size == 'Small':
         print(self.name, 'Win the fight')
     elif cat2.self == 'Big' and self.size == 'Small':
         print(cat2.name, 'Win the fight')
     else:
         print('There is no fight, they are friends')

and call by cat1.fight(cat2).

Alternatively you could just move fight out of the class and continue calling fight(cat1, cat2)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading