Re: Dynamic classes

Liste des GroupesRevenir à cl python 
Sujet : Re: Dynamic classes
De : olegsivokon (at) *nospam* gmail.com (Left Right)
Groupes : comp.lang.python
Date : 20. May 2025, 07:03:29
Autres entêtes
Message-ID : <mailman.67.1747767982.3008.python-list@python.org>
References : 1 2
I have created a dynamic class using the type() function:
x = type('MyFlags', (), {'Flag1': 1, 'Flag2': 2, 'Flag3: 4, ' '__init__' :
__init__})

I find that it's generally more convenient to do this using similar code:

def constructor(flag1, flag2):
    class _Hidden:
        def __init__(self):
            self.flag1 = flag1
            self.flag2 = flag2
    return _Hidden()

h = constructor('Flag1', 'Flag2')

This accomplishes the same goal (with some overhead, perhaps), but is
easier to format, the editor will recognize that you are writing a
class rather than a bunch of data bits, you will have the ability to
define the methods together with the class, benefit from the class
initialization environment (eg. by using @static or @property
decorators etc.). Also, this allows class parametrization in ways that
are difficult to accomplish using metaclasses and other complicated
mechanisms Python language provides to that end. Eg. you can
conditionally inherit from different superclasses (so, you can use
this approach as a factory that creates different classes), or you can
conditionally add methods, conditionally provide different method
bodies, conditionally provide different arguments to parametrized
decorators.

Date Sujet#  Auteur
20 May 25 * Re: Dynamic classes3Left Right
21 May 25 `* Re: Dynamic classes2Stefan Ram
22 May 25  `- Re: Dynamic classes (Posting On Python-List Prohibited)1Lawrence D'Oliveiro

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal