Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialElena Chen
1,503 PointsMethod argument
What's the purpose of these two? Does that mean every time I specify an argument, I need these attributes?
self.name = name
self.sneaky = sneaky
If I don't specify any argument in the method, I don't need any attributes but use "=" in the instances. Is that correct? I tried below codes:
class Animal:
def __init__(self, **kwargs):
for attribute, value in kwargs.items():
setattr(self, attribute, value)
>>> cat = Animal(name="Meow", age=2, color="grey")
>>> cat.age
2
>>> cat.color
'grey'
>>>
1 Answer
Steven Parker
231,275 PointsIf you look one line up at the definition of the constructor, you see:
def __init__(self, name, sneaky=True, **kwargs)
This shows you that when you create an instance, you must provide a "name" argument; but you can leave off a "sneaky" argument and it will be set to "True" by default).
In your second example, the arguments are all "kwargs", which are also optional but remain undefined by default.