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 trialMar Bocatcat
7,405 Points__init__,__str__ (**kwargs) ??
Hi! I just started learning OOP(and also Programming ) after getting the python Basics and Collections done , I am totally lost learning OOP. Can someone explain to me what these are , and what they do.(In 5 year old language please :) )
init str (**kwargs) and also the whole OOP idea. I am just really new to programming and i thought i had a good grasp on programming , but OOP is a totally new world. Thank you so much!
1 Answer
Charles Lee
17,825 PointsAlright Mar,
Let's break these down.
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
The init method is a special python method that is mainly used to set the attributes for a new instance. An instance, as you may know already, is a single occurrence of an object.
It is usually short for initialize
which may help you better understand the purpose of the method. It helps you initialize the instance with the passed in arguments.
def __str__(self):
return self.name
There is a common problem with simply printing an instance out. If we had an instance without setting the special str method, we would get the subjectively unhelpful similar message: <main.Example object at 0x102a080f0>. This doesn't really tell you anything about the instance itself. When you set the str method, you can now set it to print out how you want the instance to be displayed.
**kwargs
is really short for keyword arguments. You've written out methods that take in arguments but with keyword arguments we can now link passed in arguments by specifying their associated keywords also. Kwargs can be arbitrarily long which means as long as you specify both the keyword and the value, you should be able to use them within the method itself by using the keyword.
More helpful links:
http://stackoverflow.com/questions/12448175/confused-about-str-in-python http://stackoverflow.com/questions/1769403/understanding-kwargs-in-python http://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do