Re: Configuring an object via a dictionary

Liste des GroupesRevenir à cl python 
Sujet : Re: Configuring an object via a dictionary
De : toby (at) *nospam* tobiah.org (Tobiah)
Groupes : comp.lang.python
Date : 15. Mar 2024, 19:59:20
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <ut25q8$2dtqs$1@dont-email.me>
References : 1
User-Agent : Mozilla Thunderbird
On 3/15/24 02:30, Loris Bennett wrote:
Hi,
 I am initialising an object via the following:
      def __init__(self, config):
          self.connection = None
          self.source_name = config['source_name']
         self.server_host = config['server_host']

However, with a view to asking forgiveness rather than
permission, is there some simple way just to assign the dictionary
elements which do in fact exist to self-variables?
class Foo():
         def __init__(self, config):
                 for key, val in config.iteritems():
                         setattr(self, key, val)
f = Foo({'cat': 'dog'})
print(f.cat)
(outputs 'dog')

Date Sujet#  Auteur
15 Mar 24 * Configuring an object via a dictionary15Loris Bennett
15 Mar 24 +- Re: Configuring an object via a dictionary1Mats Wichmann
15 Mar 24 +- Re: Configuring an object via a dictionary1Thomas Passin
15 Mar 24 +* Re: Configuring an object via a dictionary4Tobiah
15 Mar 24 i`* Re: Configuring an object via a dictionary3Tobiah
18 Mar 24 i `* Re: Configuring an object via a dictionary2Loris Bennett
19 Mar 24 i  `- Re: Configuring an object via a dictionary1Pokemon Chw
15 Mar 24 +- Re: Configuring an object via a dictionary1Grant Edwards
15 Mar 24 +- Re: Configuring an object via a dictionary1Thomas Passin
15 Mar 24 +- Re: Configuring an object via a dictionary (Posting On Python-List Prohibited)1Lawrence D'Oliveiro
15 Mar 24 +- Re: Configuring an object via a dictionary12QdxY4RzWzUUiLuE
16 Mar 24 +- Re: Configuring an object via a dictionary1dn
16 Mar 24 +- Re: Configuring an object via a dictionary1Thomas Passin
16 Mar 24 +- Re: Configuring an object via a dictionary1<avi.e.gross
18 Mar 24 `- Re: Configuring an object via a dictionary1Anders Munch

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal