Last active
June 6, 2016 04:54
-
-
Save makmanalp/1ed561d502a48bc2d997ee63ab8d1cc9 to your computer and use it in GitHub Desktop.
Code in the body of a class - 7
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
# If you legitimately need to get in there before class definition, say because you're generating something that already has a metaclass | |
# that needs to run (e.g. dynamically generating Django models), you could use type(), like this: | |
def class_factory_1(num_attrs): | |
attrs = {"var_{}".format(i): i for i in range(num_attrs)} | |
return type("Klass", (SomeBaseClass,), attrs) | |
# Otherwise you could use a regular old class definition for a slightly less smartypants solution | |
def class_factory_2(num_attrs): | |
class Inner(object): | |
pass | |
for i in range(num_attrs): | |
setattr(Inner, "var_{}".format(i), i) | |
return Inner | |
# Or simply this, if you can wait until after __init__ | |
class Foo(object): | |
def __init__(self, num_attrs): | |
for i in range(num_attrs): | |
# or self.__class__ perhaps | |
setattr(self, "var_{}".format(i), i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment