473,233 Members | 1,673 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,233 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 1292
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: DotNetJunky | last post by:
I have built a control that runs an on-line help system. Depending on the category you selected via dropdownlist, it goes out and gets the child subcategories, and if there are any, adds a new...
3
by: Jim Heavey | last post by:
Trying to figure out the technique which should be used to add rows to a datagrid. I am thinking that I would want an "Add" button on the footer, but I am not quite sure how to do that. Is that...
9
by: friendhouston | last post by:
Hi, Have a requirement where new items may be added later to an existing list of items. These new items may have new features but will need to contain minimum basic features like description and...
5
by: Bob B. | last post by:
I've been playing with descriptors lately. I'm having one problem I can't seem to find the answer to. I want to assign a descriptor to a list of attributes. I know I should be able to add these...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...

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.