Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #197481

Re: Dynamic classes

From ram@zedat.fu-berlin.de (Stefan Ram)
Newsgroups comp.lang.python
Subject Re: Dynamic classes
Date 2025-05-19 16:33 +0000
Organization Stefan Ram
Message-ID <dynamic-20250519173131@ram.dialup.fu-berlin.de> (permalink)
References <mailman.63.1747669953.3008.python-list@python.org>

Show all headers | View raw


Jonathan Gossage <jgossage@gmail.com> 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!

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar


Thread

Dynamic classes Jonathan Gossage <jgossage@gmail.com> - 2025-05-19 11:51 -0400
  Re: Dynamic classes ram@zedat.fu-berlin.de (Stefan Ram) - 2025-05-19 16:33 +0000
    Re: Dynamic classes Greg Ewing <greg.ewing@canterbury.ac.nz> - 2025-05-20 12:29 +1200

csiph-web