Extending a class by parameter in Python

  • A+

I want to expand the class Foo by the class Bar, the issue that I have is that I can't expand it in the usual way (class Foo(Bar)) because the class Bar is somewhat dynamically generated.

I made this small example to illustrate my desired outcome:

class Bar:     def super_cool_function():         print("Cool")  class Foo:     def __init__(self, another_class):         # I want to extend Foo by another_class  # Desired result foobar = Foo(Bar) foobar.super_cool_function() 

Again this is not what I'm looking for:

class Foo(Bar):     pass  foobar = Foo() foobar.super_cool_function() 


"The class Bar is somewhat dynamically generated" That's fine... as long as it follows the blueprint (of a class that should be extended by Foo), you can leverage python closures here. Dynamically create a new class by creating it inside, and returning it from a function.

def get_class(superclass):     class Foo(superclass):         def __init__(self, ...):            ...      return Foo  DynamicFoo = get_class(Bar) myobj = DynamicFoo() 

This is a common pattern you'll see in python - leveraging closures to dynamically create callbacks and classes.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: