473,379 Members | 1,187 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,379 software developers and data experts.

Add lists to class?

I have a list with some strings in in it, 'one', 'two' 'three' and so
on. I would like to add lists to a class with those names. I have no
way of knowing what will be in the list or how long the list will be in
advance.

Something like:

class master:
def __init__(self, list):
self.count = len(list)
for line in list:
self.line = [] # obviously this doesn't work

list = ['one', 'two', 'three']

a = master(list)

so that I get:

dir(a)

['_doc__', '_init__', '_module__', 'one', 'two', 'three']

instead of:

dir(a)

['_doc__', '_init__', '_module__', 'line']
TIA,

jab

Sep 1 '05 #1
12 1338
Thanks to a generous Pyhtonista replied with a pointer to setattr().

jab

Sep 1 '05 #2
I think what you want is this (not tested):

class master:
def __init__(self, list):
self.count = len(list)
for entry in list:
self.__dict__[entry]= []
This will get you master class with three attributes

a = master(list)

a.one
a.two
a.three

each containing an empty list. You can then do things
like:

a.one.append(something)
a.three.append(something)

Larry Bates

BBands wrote:
I have a list with some strings in in it, 'one', 'two' 'three' and so
on. I would like to add lists to a class with those names. I have no
way of knowing what will be in the list or how long the list will be in
advance.

Something like:

class master:
def __init__(self, list):
self.count = len(list)
for line in list:
self.line = [] # obviously this doesn't work

list = ['one', 'two', 'three']

a = master(list)

so that I get:

dir(a)

['_doc__', '_init__', '_module__', 'one', 'two', 'three']

instead of:

dir(a)

['_doc__', '_init__', '_module__', 'line']
TIA,

jab

Sep 1 '05 #3
tested and working...

jab, now possessing an embarrassment of riches, says "Thanks!"

Sep 1 '05 #4
BBands a écrit :
(snip)
class master:
def __init__(self, list):


Don't use 'list' as an identifier, it will shadow the builtin list type.
Sep 1 '05 #5
"BBands" <bb****@gmail.com> writes:
I have a list with some strings in in it, 'one', 'two' 'three' and so
on. I would like to add lists to a class with those names. I have no
way of knowing what will be in the list or how long the list will be in
advance.


Others have told you how to do it. Now I'm going to tell you why you
shouldn't.

First, since you don't know the names of the attributes you added, you
can't possibly write code that references them in the normal way. So
is there really much point in making them an attribute at all?

Second, since you don't know the names of the attributes you added,
you don't know if one of more of them is going to clobber a feafure of
the class that you want to use for something else. I.e., consider:
class C: .... pass
.... c = C()
print c <__main__.C instance at 0x8270b4c> c.__str__ = 'foo'
print c Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object is not callable
I.e. - if someone adds a __str__ attribute to your class, you won't be
able to print it any more. Not a good thing.

In general, you probably want a dictionary instead of attributes:
class C(dict): .... def __init__(self, l):
.... for i in l:
.... self[i] = []
.... c = C(['a', 'b', 'c'])
c['a'] []


You didn't say why you wanted to do this; maybe you really do have a
good reason. But that would be an exceptional case.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Sep 2 '05 #6
Mike Meyer wrote:
"BBands" <bb****@gmail.com> writes:

I have a list with some strings in in it, 'one', 'two' 'three' and so
on. I would like to add lists to a class with those names. I have no
way of knowing what will be in the list or how long the list will be in
advance.

Others have told you how to do it. Now I'm going to tell you why you
shouldn't.

First, since you don't know the names of the attributes you added, you
can't possibly write code that references them in the normal way. So
is there really much point in making them an attribute at all?

Second, since you don't know the names of the attributes you added,
you don't know if one of more of them is going to clobber a feafure of
the class that you want to use for something else. I.e., consider:

class C:
... pass
...
c = C()
print c
<__main__.C instance at 0x8270b4c>
c.__str__ = 'foo'
print c
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object is not callable
I.e. - if someone adds a __str__ attribute to your class, you won't be
able to print it any more. Not a good thing.

In general, you probably want a dictionary instead of attributes:

class C(dict):
... def __init__(self, l):
... for i in l:
... self[i] = []
...
c = C(['a', 'b', 'c'])
c['a']


[]

and 2c more to use attributes but prevent overriding of real attributes

def __getattr__(self,name):
if name in self:
return self[name]
raise AttributeError

Paolino

___________________________________
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB
http://mail.yahoo.it
Sep 2 '05 #7
That's interesting and I take your point. Maybe there is a better way.
Here is what I am doing now. (working)

I start with a text file of ticker symbols. I read each symbol and
stick it in a list, retrieve the data for it from MySQL, do a trivial
smoothing and pass the data to a modeling routine. I read the tickers
into a list, self.symbols. Then for each ticker I create a list,
self._0, self._1, ... and a list for the smoothed values,
self._0_smooth, self._1_smooth, ... I end up with data I can access
with self.__dict__["_" + str(var)] and a matching symbol which I can
access self.symbols[var].

Ideas for a better approach gladly accepted.

jab

Sep 2 '05 #8
That's interesting and I take your point. Maybe there is a better way.
Here is what I am doing now. (working)

I start with a text file of ticker symbols. I read each symbol and
stick it in a list, retrieve the data for it from MySQL, do a trivial
smoothing and pass the data to a modeling routine. I read the tickers
into a list, self.symbols. Then for each ticker I create a list,
self._0, self._1, ... and a list for the smoothed values,
self._0_smooth, self._1_smooth, ... I end up with data I can access
with self.__dict__["_" + str(var)] and a matching symbol which I can
access self.symbols[var].

Ideas for a better approach gladly accepted.

jab

Sep 2 '05 #9
BBands wrote:
I start with a text file of ticker symbols. I read each symbol and
stick it in a list, retrieve the data for it from MySQL, do a trivial
smoothing and pass the data to a modeling routine. I read the tickers
into a list, self.symbols.
OK...
Then for each ticker I create a list,
self._0, self._1, ...
That's not a list. That's a bunch of attributes.
I end up with data I can access
with self.__dict__["_" + str(var)] and a matching symbol which I can
access self.symbols[var]. Ideas for a better approach gladly accepted.


Why don't you use a real list instead? I don't understand what
self.__dict__["_" + str(var)] gets you.

self.symbols = ["IBM", "MSFT", "SCOX"]
self.values = [99, 100, 0.25]
self.smooth_values = [100, 100, 0]

or you could use a dict:

self.values = dict(IBM=99, MSFT=100, SCOX=0.25)
--
Michael Hoffman
Sep 2 '05 #10
> Why don't you use a real list instead?

I am using lists... I just showed the naming schema. Here is how they
are implemented.

for var in range(len(self.symbols)):
setattr(self, "_" + str(var), [])
I don't understand what
self.__dict__["_" + str(var)] gets you.


It let's me access lists that aren't known at write time.

jab

Sep 2 '05 #11
"BBands" <bb****@gmail.com> writes:
Why don't you use a real list instead?


I am using lists... I just showed the naming schema. Here is how they
are implemented.

for var in range(len(self.symbols)):
setattr(self, "_" + str(var), [])


That's not the list he's talking about. And I agree with him.

Why are you setting the attreibutes "_" + str(var)? Why not just store
them in a dictionary?
I don't understand what
self.__dict__["_" + str(var)] gets you.

It let's me access lists that aren't known at write time.


Yes, but it's ugly, makes one address space server for two different
sets of variables, and has potential for some nasty bugs. Why not just
do:

self.lists[var] = []

Or, if you're really tied to "_", do:

self._[var] = []

Or, given that your example used increasing numeric names, just use a
list here:

self._.append([])

which you would then reference as self._[0], self._[1], etc.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Sep 4 '05 #12
Paolino <pa*************@tiscali.it> writes:
Mike Meyer wrote:
"BBands" <bb****@gmail.com> writes:
I have a list with some strings in in it, 'one', 'two' 'three' and so
on. I would like to add lists to a class with those names. I have no
way of knowing what will be in the list or how long the list will be in
advance.

Others have told you how to do it. Now I'm going to tell you why you
shouldn't.
First, since you don't know the names of the attributes you added,
you
can't possibly write code that references them in the normal way. So
is there really much point in making them an attribute at all?
Second, since you don't know the names of the attributes you added,
you don't know if one of more of them is going to clobber a feafure of
the class that you want to use for something else. I.e., consider:
>class C:

... pass
...
>c = C()
>print c

<__main__.C instance at 0x8270b4c>
>c.__str__ = 'foo'
>print c

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object is not callable
I.e. - if someone adds a __str__ attribute to your class, you won't
be
able to print it any more. Not a good thing.
In general, you probably want a dictionary instead of attributes:
>class C(dict):

... def __init__(self, l):
... for i in l:
... self[i] = []
...
>c = C(['a', 'b', 'c'])
>c['a']

[]

and 2c more to use attributes but prevent overriding of real attributes

def __getattr__(self,name):
if name in self:
return self[name]
raise AttributeError


Good point. The problem with this is that your real attributes will
now hide things stored in the dictionary. The bugs I listed above are
all caused by trying to conflate two different name spaces: the
attributes of the object and the variables stored in it as
data. Separating them out and then layering one back on top of the
other just gives you those bugs back.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Sep 4 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Alan Little | last post by:
I need to merge and de-duplicate some lists, and I have some code which works but doesn't seem particularly elegant. I was wondering if somebody could point me at a cleaner way to do it. Here's...
7
by: Chris Ritchey | last post by:
Hmmm I might scare people away from this one just by the title, or draw people in with a chalange :) I'm writting this program in c++, however I'm using char* instead of the string class, I am...
1
by: Jacek Dziedzic | last post by:
Hi! A) Why isn't it possible to set a member of the BASE class in an initialization list of a DERIVED class constructor (except for 'calling' the base constructor from there, of course)? I even...
2
by: Skywise | last post by:
I am fairly new to linked lists. I am trying to write a class using linked lists. It seems to work fine, but I need to know if I have any resource leaks in it because I plan on using this class...
4
by: Christian Christmann | last post by:
Hi, I've some old code which I would like to replace by STL. It's a self-written double linked list which consists of instances of another class Element which contains the information as void*...
7
by: Christian Christmann | last post by:
Hi, in the past I always appreciated your help and hope that you also can help me this time. I've spent many many hours but still can't solve the problem by myself and you are my last hope. ...
1
by: andrew | last post by:
Hi, I'm a C++ newbie, so apologies for this rather basic question. I've searched for help and, while I understand the problem (that the outer class is not yet defined), I don't understand what...
1
by: Simon Forman | last post by:
I've got a function that I'd like to improve. It takes a list of lists and a "target" element, and it returns the set of the items in the lists that appear either before or after the target...
2
by: Christian Chrismann | last post by:
Hi, an application uses a wrapper class for an STL list. Basically, this template class provides the same functions (delete, append, find...) as an ordinary STL list. Additionally, there are...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.