I have to create a class with two methods. This is the exercise:
This is my attempted code:
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:
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)

