+ 1
In the code in the description, how come 'self' is an argument of the class 'Cat', yet only 'color' and 'legs' is plugged in?
class Cat: def __init__(self, color, legs): self.color = color self.legs = legs felix = Cat("ginger", 4) rover = Cat("dog-colored", 4) stumpy = Cat("brown", 3)
2 ответов
+ 3
color and legs are the arguments handed over to the class when you make one of these cats. They don't belong to the class yet.
Then, inside the constructor function, these arguments are used to create the attributes for the cat.
So self.color = color
means:
Please take the color I gave you and make it the color of 'self', self being the cat.
+ 1
Thanks, HonFu