Re: Dynamic classes

[email protected] (Stefan Ram) 19 May 2025 16:33:21 GMT
Newsgroups comp.lang.python
Organization Stefan Ram
Message-ID <[email protected]>
Jonathan Gossage <[email protected]> wrote or quoted:
>I have created a dynamic class using the type() function:
>x = type('MyFlags', (), {'Flag1': 1, 'Flag2': 2, 'Flag3: 4, ' '__init__' :
>__init__})
>The new class is there, and the class variables, Flag1, Flag2, and Flag3,
>are present correctly. However, when I try to create an instance of this
>class with the following code:
>y = x('Flag1', 'Flag2')
>it fails with a TypeError stating that 'MyFlags' does not accept arguments.
>What do I have to do to make this happen?. BTW __init__(self, *args) is
>defined as the instance initializer.

  Excellent question! So, the reason you're getting that
  TypeError is your __init__ function isn't actually hooked up
  right when you build your class with "type". You got to set up
  your init before you call "type", and then drop it into the
  class dictionary as a /function/ (not as a string). Also, looks
  like you've got a typo in the Flag3 line - missing a quote.

  Here's how you want to do it:

def __init__(self, *args):
    self.flags = args

x = type(
    'MyFlags',
    (),
    {
        'Flag1': 1,
        'Flag2': 2,
        'Flag3': 4,
        '__init__': __init__
    }
)

y = x('Flag1', 'Flag2')

print(y.flags)  # Output: ('Flag1', 'Flag2')

  Basically, "type" needs the actual function object for
  "__init__", not just the name. If you mess that up or have 
  a typo, Python just falls back on the default init, which doesn't
  take any arguments, and that's why you get the error.

  Here's the rundown:

  Problem: "__init__" isn't set up right
  Fix: Define "__init__" before calling "type"

  Problem: Typo in your dict
  Fix: Make sure it's 'Flag3': 4

  Problem: Wrong reference
  Fix: Pass the function, not a string

  Once you clean that up, your class should take arguments just fine!