Created
December 13, 2015 05:35
-
-
Save noodlebreak/37402a826190d1121fd3 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
# 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