2

Possible duplicates: Is there a way to create subclasses on-the-fly? Dynamically creating classes - Python

I would like to create a subclass where the only difference is some class variable, but I would like everything else to stay the same. I need to do this dynamically, because I only know the class variable value at run time.

Here is some example code so far. I would like FooBase.foo_var to be "default" but FooBar.foo_var to be "bar." No attempt so far has been successful.

class FooBase(object):
    foo_var = "default"

    def __init__(self, name="anon"):
        self.name = name

    def speak(self):
        print self.name, "reporting for duty"
        print "my foovar is '" +  FooBase.foo_var + "'"


if __name__ == "__main__":
    #FooBase.foo_var = "foo"
    f = FooBase()
    f.speak()

    foobarname = "bar"
    #FooBar = type("FooBar", (FooBase,), {'foo_var': "bar"})
    class FooBar(FooBase): pass
    FooBar.foo_var = "bar"
    fb = FooBar()
    fb.speak()

Many thanks

EDIT so I obviously have a problem with this line:

print "my foovar is '" + FooBase.foo_var + "'"

The accepted answer has self.foo_var in the code. That's what I should be doing. I feel ridiculous now.

1 Answer 1

3

What about this:

def make_class(value):
  class Foo(object):
    foo_var = value

    def speak(self):
      print self.foo_var
  return Foo

FooBar = make_class("bar")
FooQux = make_class("qux")

FooBar().speak()
FooQux().speak()

That said, can't you make the value of foo_var be a instance variable of your class? So that the same class instantiated with different input behaves in different ways, instead of creating a different class for each of those different behaviours.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I was missing self.foo_var. The reason I preferred to have a class variable instead of an instance variable, is I'll have zillions of instances, but probably 1-3 subclasses.
Based on that motivation only, I think you should make foo_var an instance variable. Creating those instances of yours will be just as fast with our without an instance variable. It sounds like you are trying to optimise something without needing too.
yes, you're right. I have pressure to optimize this as much as possible. I will try with/without class variable and see if there's any difference (probably not)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.