Re: Dynamic classes

Liste des GroupesRevenir à cl python 
Sujet : Re: Dynamic classes
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.python
Date : 19. May 2025, 17:33:21
Autres entêtes
Organisation : Stefan Ram
Message-ID : <dynamic-20250519173131@ram.dialup.fu-berlin.de>
References : 1
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!



Date Sujet#  Auteur
19 May 25 * Dynamic classes3Jonathan Gossage
19 May 25 `* Re: Dynamic classes2Stefan Ram
20 May 25  `- Re: Dynamic classes1Greg Ewing

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal