Frage

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.

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top