Created
September 25, 2018 04:05
-
-
Save AugFJTan/9f8e0a5889a8b8331918035116006e73 to your computer and use it in GitHub Desktop.
Quirky Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# File : quirky_python.py | |
# Author: AugFJTan | |
# Date : 25/09/18 | |
############################################ | |
# Swap values without a temporary variable # | |
############################################ | |
# Initial values | |
a = 5 | |
b = 2 | |
# Expect "a = 5, b = 2"; nothing unusual here | |
print("a = {0}, b = {1}".format(a, b)) | |
# Swap 'em! | |
a, b = b, a | |
# Output is "a = 2, b = 5"! | |
print("a = {0}, b = {1}".format(a, b)) | |
############################################ | |
# Lists and tuples: similar but different? # | |
############################################ | |
# Yes, these are valid, but are they equivalent? | |
L = [3.5, "Hello", 124] | |
T = (3.5, "Hello", 124) | |
# Print list | |
for l in L: | |
print(l) | |
# Print tuple | |
for t in T: | |
print(t) | |
# Assign value | |
L[0] = 7.2 # No problem here | |
T[0] = 7.2 # Error! | |
################ | |
# Nested lists # | |
################ | |
L = [3, [4,5], [[6]]] | |
for l in L: | |
print(l) | |
# Output: | |
# 3 | |
# [4, 5] | |
# [[6]] | |
################### | |
# Lists in tuples # | |
################### | |
# We saw that tuples are immutable, | |
# but then again, lists are mutable... | |
T = (2.6, "Hello", [4,5,6]) | |
T[2].append(7) # Totally valid! | |
############################################### | |
# All class variables and methods are public! # | |
############################################### | |
# Access modifiers? Pfft... who needs such complex abstractions? | |
class Test: | |
def __init__(self): | |
self.public = "Public!" | |
self.protected = "Some sensitve data" | |
self.private = "Top secret info" | |
def private_method(self): | |
return "Encryption key" | |
t = Test() | |
t.public | |
# Nothing will stop you from doing this: | |
t.private | |
t.protected | |
t.private_method() | |
# Instead, use convensions to denote private and protected | |
class Test: | |
def __init__(self): | |
self.public = "Public!" | |
self._protected = "Some sensitve data" | |
self.__private = "Top secret info" | |
def __private_method(self): | |
return "Encryption key" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment