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.
CodePudding user response:
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)
CodePudding user response:
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')
Move the fight function outside of your class.
CodePudding user response:
That's because fight
is a method of the class Cats() (recommendation, don't use plural on classes names because an object is a Cat, not many Cats). As fight
is a method, a Cat object has to call it, that is cat1.fight(cat2)
, e.g.
Another solution, if you want keep the function independent of the object, you have to define fight
out of the class. That is:
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')