Skip to content

Instantly share code, notes, and snippets.

@dev-dull
Last active June 5, 2019 23:59
Show Gist options
  • Select an option

  • Save dev-dull/ce2e509cbe2bb195fcd59a9439c37098 to your computer and use it in GitHub Desktop.

Select an option

Save dev-dull/ce2e509cbe2bb195fcd59a9439c37098 to your computer and use it in GitHub Desktop.
##
## selfie.py
## Quick illustration of the 'self' keyword
## Illustration of `if __name__ == '__main__'`
##
##
## Read through the below code and comments, then try the following commands
## python3 selfie.py # see everything that is printed to screen
## python3 # see that the code outside the class and the __name__ if condition is run
## >>> from selfie import Selfie
## >>> exit()
## python3
## >>> import selfie
##
class Selfie(object):
def __init__(self, bar):
self.bar = bar # take our input and save it into self.bar which can be accessed by other fuctions.
self.foobar = bar # the variable name in the class doesn't need to match, though.
baz = bar # this is only visible in the __init__ funciton
def print_bars(self):
self.foobar += 1 # we can change it here and it will be changed throughout the whole class
print(self.bar, self.foobar) # we can access both of our 'bar' variables
def print_foobar(self):
print(self.foobar) # just to see our change from print_bars()
def print_baz(self):
try:
print(baz) # whoops. baz doesn't appear to exist yet because it was defined to only exist in __init__
except Exception as e:
print('This prints out because the baz variable does not exist in this scope.')
baz = self.bar
print('Okay, now baz exists and is %s' % baz)
# print('Okay, now bar exists and is {baz}') # New python syntax. I haven't tried this new feature yet.
if __name__ == '__main__':
# these will only happen when we run `python3 selfie.py` from the command line.
example = Selfie(11) # create an instance of the object
example.print_bars()
example.print_foobar()
example.print_baz()
example2 = Selfie(0)
example2.print_bars() # This will happen every time: `from selfie import Selfie`, `import selfie` and on the command line when we `python3 selfie.py`
# I abuse this fact in some of my code, but you generally don't want any logic outside of a function or outside of a class.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment