Skip to content

Instantly share code, notes, and snippets.

@ssaamm
Created March 27, 2017 12:56
Show Gist options
  • Save ssaamm/9c861c9aa5d6b56f591c1f5f6e7af629 to your computer and use it in GitHub Desktop.
Save ssaamm/9c861c9aa5d6b56f591c1f5f6e7af629 to your computer and use it in GitHub Desktop.
Python addendum to Metz's Practical Object-Oriented Design in Ruby
# 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']
# ...
from some_framework import Wheel
import gear_wrapper
print(gear_wrapper.gear(chainring=52, cog=11, wheel=Wheel(26, 1.5)).gear_inches)
import some_framework
def gear(**kwargs):
return some_framework.Gear(kwargs['chainring'], kwargs['cog'], kwargs['wheel'])
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