Skip to content

Instantly share code, notes, and snippets.

@AugFJTan
Created September 25, 2018 04:05
Show Gist options
  • Save AugFJTan/9f8e0a5889a8b8331918035116006e73 to your computer and use it in GitHub Desktop.
Save AugFJTan/9f8e0a5889a8b8331918035116006e73 to your computer and use it in GitHub Desktop.
Quirky Python
# 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