471,353 Members | 1,781 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,353 software developers and data experts.

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......with 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
Sep 2 '07 #1
5 1214
Nathan Harmston <ra*********@googlemail.comwrote:
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......with 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
Sep 2 '07 #2
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(self,name,value=None):
setattr(self,name, value)

def newAttribute2(self,name,value=None):
self.__setattr__(name, value)

def dump(self):
for self.y in self.__dict__.keys():
yield self.y + "=" + getattr(self,self.y)

p1 = Person()
p1.newAttribute('fname','Brian')
p1.newAttribute('lname','Munroe')
p1.newAttribute2("mi","E")

for x in p1.dump():
print x

Sep 2 '07 #3
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:
http://www.python.org/doc/lib/built-in-funcs.html

# __setattr__ etc.
http://www.python.org/doc/ref/attribute-access.html

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.
Sep 2 '07 #4
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

Sep 3 '07 #5
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

Sep 3 '07 #6

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Jim Heavey | last post: by
9 posts views Thread by friendhouston | last post: by
5 posts views Thread by Bob B. | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.