Skip to content

Instantly share code, notes, and snippets.

@noodlebreak
Created December 13, 2015 05:35
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 noodlebreak/37402a826190d1121fd3 to your computer and use it in GitHub Desktop.
Save noodlebreak/37402a826190d1121fd3 to your computer and use it in GitHub Desktop.
# Modified version of PowerMeta from
# http://www.pydanny.com/python-partials-are-fun.html
from functools import partial
def power(base, exponent):
return base ** exponent
class Power(object):
def __init__(self):
# generate 50 partial power functions:
for x in range(1, 51):
# Set the partials to the class
setattr(
# cls represents the class
Power,
# name the partial
"p{}".format(x),
# partials created here
partial(power, exponent=x)
)
# super(Power, cls).__init__(name, bases, dct)
p = Power()
print("\nUsing instances")
for i in range(1, 4):
print("%d^2: %d" % (i, p.p2(i)))
# Prints:
# Using instances
# 1^2: 1
# 2^2: 4
# 3^2: 9
print("\nUsing class (no instantiation)")
for i in range(1, 4):
print("%d^2: %d" % (i, Power.p2(i)))
# Prints:
# Using class (no instantiation)
# 1^2: 1
# 2^2: 4
# 3^2: 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment