0
What does "4" in felix= Cat("ginger", 4) mean?
class Cat: def __init__(self, color, legs): self.color = color self.legs = legs felix = Cat("ginger", 4) print(felix.color)
3 Answers
+ 2
It means that your cat has 4 legs.
+ 2
It is the 2nd attributes(leg) of cat. When you are calling the class function, it will be intialized with the attributes you sent along.
+ 1
so when you create a new instance of a particular class, like in the line
felix = Cat("ginger", 4)
the init method of the relevant class is called, a bit like if you where calling a function with that name, except the parameters you give go in from the second parameter in the definition, rather than matching up exactly.
so you are calling __init__(self, "ginger", 4)
then in the init method we can save the values passed in, into attributes of the object. We could also alter the values, or do other stuff with the parameters given rather than just directly saving them to the object
try changing the code into
class Cat:
def __init__(self, color, legs):
print(color)
print("we passed in " + str(legs) " for legs")
modifiedLegs = legs - 1
#self is the particular copy of Cat that we are creating during this init, so in the next line ThisParticularCopyOfCat.color is set to the thing we passed in for color
self.color = color
# so with self being Felix this next line makes Felix.legs become the value that we have in modifiedLegs
self.legs = modifiedLegs
Felix = Cat("ginger", 4)
print(Felix.color)
print(Felix.legs)
and just running that, see if it makes more sense, and then mess with different code in the init