Last active
March 2, 2016 03:06
-
-
Save garybernhardt/fe5492538302728737bc to your computer and use it in GitHub Desktop.
This file contains 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
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