0

I have well know class and I need to dynamically generate some nested classes for the well known class.

How do I accomplish this?


def AddNestedClasses(cls):
    inner1  = type("Inner")
    # How do I inject the class 'Inner' into 'cls'?
    return cls

@AddNestedClasses
class Outer:
    pass
4
  • 1
    How about setattr(cls, 'Inner', inner1)? By the way, type("Inner") is always the class str - is that what you intended? Commented Jan 28, 2020 at 22:00
  • You could also do it using inheritance instead of a decorator. Commented Jan 28, 2020 at 22:01
  • What do you mean by a "well known" class? What would be a "not well known" class? Commented Jan 28, 2020 at 22:04
  • Thank you, that works. I changed the parameter passed to type to type("Inner", (), {}) to stop getting a string. And then I set the property 'Inner' as suggested above to 'inner1' and that worked. I dir the class and it has a nested class "Inner". Commented Jan 28, 2020 at 22:11

1 Answer 1

2
def AddNestedClasses(cls):
    inner1  = type("Inner", (), {})
    cls.Inner = inner1
    return cls

@AddNestedClasses
class Outer:
    pass

print(dir(Outer))
Sign up to request clarification or add additional context in comments.

Comments

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.