Created
March 27, 2017 12:56
-
-
Save ssaamm/9c861c9aa5d6b56f591c1f5f6e7af629 to your computer and use it in GitHub Desktop.
Python addendum to Metz's Practical Object-Oriented Design in Ruby
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
# For original code, see "some_framework.py" | |
# Remove Argument-Order Dependencies | |
# First code example under "Use Hashes for Initialization Arguments" | |
class Gear(object): | |
def __init__(self, **kwargs): | |
self.chainring = kwargs['chainring'] | |
self.cog = kwargs['cog'] | |
self.wheel = kwargs['wheel'] | |
# ... | |
print(Gear(chainring=52, cog=11, wheel=Wheel(26, 1.5)).gear_inches) | |
# "Explicitly Define Defaults" | |
class Gear(object): | |
def __init__(self, chainring=40, cog=18, **kwargs): | |
self.chainring = chainring | |
self.cog = cog | |
self.wheel = kwargs['wheel'] | |
# ... |
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 some_framework import Wheel | |
import gear_wrapper | |
print(gear_wrapper.gear(chainring=52, cog=11, wheel=Wheel(26, 1.5)).gear_inches) |
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
import some_framework | |
def gear(**kwargs): | |
return some_framework.Gear(kwargs['chainring'], kwargs['cog'], kwargs['wheel']) |
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 | |
class Wheel(namedtuple('Wheel', 'rim tire')): | |
@property | |
def diameter(self): | |
return self.rim + (self.tire * 2) | |
class Gear(object): | |
def __init__(self, chainring, cog, wheel): | |
self.chainring = chainring | |
self.cog = cog | |
self.wheel = wheel | |
@property | |
def ratio(self): | |
return self.chainring / self.cog | |
@property | |
def gear_inches(self): | |
return self.ratio * self.wheel.diameter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment