Skip to content

Instantly share code, notes, and snippets.

@garybernhardt
Last active March 2, 2016 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garybernhardt/fe5492538302728737bc to your computer and use it in GitHub Desktop.
Save garybernhardt/fe5492538302728737bc to your computer and use it in GitHub Desktop.
from collections import namedtuple
from datetime import date
# Here's a user defined using the usual "OO" style.
class UserClass:
def __init__(self, first, last, birthday):
self.__first = first
self.__last = last
self.__birthday = birthday
def name(self):
return self.__first + " " + self.__last
def age(self):
return date.today() - self.__birthday
# Here's an "object" with identical external semantics defined using a
# namedtuple (basically a struct) and a closure.
User = namedtuple("User", ["name", "age"])
def newUser(first, last, birthday):
return User(
name=lambda: first + " " + last,
age=lambda: date.today() - birthday)
# Instantiate one of each, with identical syntax other than the name of the
# class vs. instantiating function.
class_john = UserClass("John", "Coltrane", date(1926, 9, 23))
struct_john = newUser("John", "Coltrane", date(1926, 9, 23))
# Print ages and names, again with identical syntax; these will be identical.
print(class_john.name())
print(struct_john.name())
print(class_john.age())
print(struct_john.age())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment