Adding attributes stored in a list to a class dynamically.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Nathan Harmston

    Adding attributes stored in a list to a class dynamically.

    Hi,

    Sorry if the subject line of post is wrong, but I think that is what
    this is called. I want to create objects with

    class Coconuts(object ):
    def __init__(self, a, b, *args, **kwargs):
    self.a = a
    self.b = b

    def spam( l )
    return Coconuts( l.a, l.b, l.attributes )

    l in a parse line of a file which is a tuple wrapped with
    attrcol......wi th attributes a, b and attributes (which is a list of
    strings in the format key=value ie...
    [ "id=bar", "test=1234" , "doh=qwerty " ] ).

    I want to add attributes to Coconuts so that I can do
    print c.id, c.test, c.doh

    HOwever I m not sure how to do this:

    how can i assign args, kwargs within the constructor of coconuts and
    how can I deconstruct the list to form the correct syntax to be able
    to be used for args, kwargs.

    HOpe this makes sense,

    Thanks in advance,

    Nathan
  • Alex Martelli

    #2
    Re: Adding attributes stored in a list to a class dynamically.

    Nathan Harmston <ratchetgrid@go oglemail.comwro te:
    Hi,
    >
    Sorry if the subject line of post is wrong, but I think that is what
    this is called. I want to create objects with
    >
    class Coconuts(object ):
    def __init__(self, a, b, *args, **kwargs):
    self.a = a
    self.b = b
    >
    def spam( l )
    return Coconuts( l.a, l.b, l.attributes )
    >
    l in a parse line of a file which is a tuple wrapped with
    attrcol......wi th attributes a, b and attributes (which is a list of
    strings in the format key=value ie...
    [ "id=bar", "test=1234" , "doh=qwerty " ] ).
    >
    I want to add attributes to Coconuts so that I can do
    print c.id, c.test, c.doh
    >
    HOwever I m not sure how to do this:
    >
    how can i assign args, kwargs within the constructor of coconuts and
    how can I deconstruct the list to form the correct syntax to be able
    to be used for args, kwargs.
    If you want to pass the attributes list it's simpler to do that
    directly, avoiding *a and **k constructs. E.g.:

    def __init__(self, a, b, attrs):
    self.a = a
    self.b = b
    for attr in attrs:
    name, value = attr.split('=')
    setattr(self, name, value)

    You may want to add some better error-handling (this code just raises
    exceptions if any item in attrs has !=1 occurrences of the '=' sign,
    etc, etc), but I hope this gives you the general idea.

    Note that you'll have trouble accessing attributes that just happen to
    be named like a Python keyword, e.g. if you have "yield=23" as one of
    your attributes you will NOT be able to just say c.yield to get at that
    attribute. Also, I'm assuming it's OK for all of these attributes'
    values to be strings, etc, etc.


    Alex

    Comment

    • Brian Munroe

      #3
      Re: Adding attributes stored in a list to a class dynamically.

      On Sep 2, 11:46 am, al...@mac.com (Alex Martelli) wrote:
      If you want to pass the attributes list it's simpler to do that
      directly, avoiding *a and **k constructs. E.g.:
      >
      def __init__(self, a, b, attrs):
      self.a = a
      self.b = b
      for attr in attrs:
      name, value = attr.split('=')
      setattr(self, name, value)
      >
      Alex:

      Thanks for the example. I too had been wondering about this for a
      while.

      One question though, which I haven't been able to find the answer from
      scouring the internet. What is the difference between calling
      __setattr__ and setattr or __getattr__ and getattr, for that matter?
      >From my example that follows, it doesn't seem to make a difference?
      thanks

      -- brian

      class Person(object):

      def __init__(self):
      pass

      def newAttribute(se lf,name,value=N one):
      setattr(self,na me, value)

      def newAttribute2(s elf,name,value= None):
      self.__setattr_ _(name, value)

      def dump(self):
      for self.y in self.__dict__.k eys():
      yield self.y + "=" + getattr(self,se lf.y)

      p1 = Person()
      p1.newAttribute ('fname','Brian ')
      p1.newAttribute ('lname','Munro e')
      p1.newAttribute 2("mi","E")

      for x in p1.dump():
      print x

      Comment

      • Steven D'Aprano

        #4
        Re: Adding attributes stored in a list to a class dynamically.

        On Sun, 02 Sep 2007 21:41:43 +0000, Brian Munroe wrote:
        One question though, which I haven't been able to find the answer from
        scouring the internet. What is the difference between calling
        __setattr__ and setattr or __getattr__ and getattr, for that matter?
        Have you read the following?

        # setattr, getattr, delattr:
        The official home of the Python Programming Language


        # __setattr__ etc.


        If there is anything unclear about the descriptions, please ask.

        In a nutshell, like all double-underscore methods, __setattr__ are for
        overriding behaviour in your own classes. With very few exceptions, you
        shouldn't need to directly call double-underscore methods (although you
        often may _write_ double-underscore methods).



        --
        Steven.

        Comment

        • Brian Munroe

          #5
          Re: Adding attributes stored in a list to a class dynamically.

          On Sep 2, 3:33 pm, Steven D'Aprano <st...@REMOVE-THIS-
          cybersource.com .auwrote:
          >
          In a nutshell, like all double-underscore methods, __setattr__ are for
          overriding behaviour in your own classes. With very few exceptions, you
          shouldn't need to directly call double-underscore methods (although you
          often may _write_ double-underscore methods).
          >
          I think I understand. You are saying that if I wanted to override the
          normal behavior when doing something like

          p1.firstName = "Brian"

          then I'd override __setattr__()?

          But if I am doing something like creating dynamic attributes, the more
          'correct' way is to use setattr? Even though they both appear to do
          the same thing, the more Pythonic way is to never directly call magic
          methods (if you can help it)?

          thanks

          -- brian

          Comment

          • Brian Munroe

            #6
            Re: Adding attributes stored in a list to a class dynamically.

            On Sep 3, 6:34 am, Steven D'Aprano <st...@REMOVE-THIS-
            cybersource.com .auwrote:
            The underscore versions are for customizing the lookup process, not for
            dynamically looking up names. If your class needs to do something non-
            standard when you write obj.name, you might need to write methods
            __getattr__ etc.
            >
            I absolutely understand that much.
            >
            In a nutshell: getattr() etc. are for looking up attributes dynamically
            when you don't know the name of the attribute until runtime. __getattr__
            etc. are for looking up attributes when you need to compute the value on
            the fly. (But an easier, less troublesome way of doing that
            is with properties.)
            >
            If I think about this in the context of a property, which in my newbie
            mind gives you the ability to 'override' the standard behavior when
            getting, setting or I suppose deleting a specific attribute. I think
            I understand what you meant by 'compute the value on the fly', the
            keyword being *compute*?

            thanks for taking the time to explain this (over and over, heh!)

            -- brian

            Comment

            Working...