473,804 Members | 1,974 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1372
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(so mething)
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.c om> 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.or g> 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.c om> 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__(sel f,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_val ues = [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

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

Similar topics

5
4506
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 my function: +++++++++++++++++++ from sets import Set
7
4834
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 ordered by my instructor and she does have her reasons so I have to use char*. So there is alot of c in the code as well Anyways, I have a linked list of linked lists of a class we defined, I need to make all this into a char*, I know that I...
1
4161
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 tried prefixing them with BASE:: but to no avail. Still it's ok when I set them in the construtor body, not the init list. Does this mean that it's a small advantage of the initialization inside the constructor over initialization in the init...
2
1392
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 quite a bit in my program. By the way, I am not a student hoping someone will do my work for me (the "cout"s are going to be taken out when I finalize the class... there just for debugging purposes now). This code is part of a computer program I...
4
2346
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* (I'm going to replace the void* by a template but that's not an issue here). The class Element is defined as: class Element
7
1816
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. I've a program which is using self-written double-linked lists as a data structure. The template list consists of list elements and the list itself linking the list elements.
1
1498
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 the "correct" solution would be. I am trying to model lists much like in Lisp, using a "Cons" object to hold two pointers - one to an Element, and the other to a further Cons. Cons is a subclass of Element, so lists can be nested.
1
1690
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 item. (Actually, it's a generator, and I use the set class outside of it to collect the unique items, but you get the idea. ;-) ) data = , , ,
2
2876
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 some convenient functions for iterating through the list. For instance, to go through all elements of the list (after fetching the first list element), the class provides a function that looks as follows:
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10356
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10361
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10103
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9179
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7644
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5536
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5676
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3839
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.