Question

Due to the wierdness of the particular module I am working with, I am wondering if there is a general way for one class to inherit the properties of another class that is locally created in a method. For example, something the following:

def DefForm():
    class F(object):
        foo = bar

    return F

class MyClass(DefForm):
    pass

m = myClass()
m.foo
>>> 'bar'
Was it helpful?

Solution

Inherit your class from the return value of the function not the function itself:

class MyClass(DefForm()):
     ...

Classes in Python are plain objects and when you're inheriting from one, you're also just inheriting from an object.

For instance, this also works:

class Foo(Bar if x == 3 else Baz):
    ...

In fact, I can't think of a situation where this wouldn't work. Even this is perfectly valid:

try:
    ...
except (FooExc if x == 3 else BarExc):
    ...

So not only are classes objects in Python, they are also treated as objects in all situations.

On a more general note, generating classes is called metaprogramming; it's a common practice in many languages (both dynamic as well as compiled and statically typed) and there's generally nothing "weird" about code that does this, as long as sanity and readability are maintained. It's as normal as creating and returning functions from other functions (which is extremely prevalent in Functional Programming), or in fact returning any object.

OTHER TIPS

Try this:

def DefForm():
    class F(object):
        foo = bar

    return F

FClass = DeftForm()

class MyClass(FClass):
    pass

m = myClass()
m.foo
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top