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 trialjiwon hwang
3,021 Pointswhat is 'return' exactly? how it works exactly?
import random
class Thief: sneaky = True
def pickpocket(self):
if self.sneaky: # it binds the attributes with the given arguments.
return bool(random.randint(0, 1 )) # to execute this statement, we should import 'random'
return False
def hide(self, light_level):
if self.sneaky and light_level < 10:
return True
return False
kenneth = Thief()
print(kenneth.hide(5)) # True print(kenneth.hide(15)) # False
import random
class Thief: sneaky = True
def pickpocket(self):
if self.sneaky: # it binds the attributes with the given arguments.
return bool(random.randint(0, 1 )) # to execute this statement, we should import 'random'
return False
that;s a part im wondering !!
def hide(self, light_level):
return self.sneaky and light_level < 10
return False
i got it exactly. But what wonders is that if i replace a code inside hide method written like "if self.sneaky and light_level < 10 return True" with "return self.sneaky and light_level < 10", the output exactly the same.
I thought i understood what 'return' is, but it doesnt look like 'return' and 'if' are different.
And, as far as I know, self inside of a method is called an argument. But i found something like "self is an instance and it binds the attributes with the given arguments"
I'm really wondering why the below code is worked and what 'self' is called exactly when it comes to vocabulary.
1 Answer
Steven Parker
231,248 PointsA "return
" ends the function, and optionally passes back a value to the caller. The ones here do both.
What you've done is to optimize the code a bit, by eliminating the conditional and returning the comparison value directly. You can go one step further by removing the "return False
" line since it will never be reached now.
And "self
" is perhaps more accurately described as a parameter, which happens to contain a reference to the current object instance and can be used to access attributes (as shown in these examples).