addvalue, how do i implement the code?
Remco Gerlich
scarblac-spamtrap at pino.selwerd.nl
Wed May 17 11:59:18 EDT 2000
Shaun wrote in comp.lang.python:
>
> right lads heres what im trying todo:
> i make an empty list, (start=[])
> what i want to do is then add a name value pair say...('shaun',20)
> to the empty list,
> ive got a feeling the code looks somthing like what below but im not sure
> how to implement it can any of yous help me out on that one?
> Shaun
>
> >>> class addv:
> def add(self,x,y):
> print'does not print'
> def __init__(self,start=[]):
> self.data=start
> def __add__(self,other):
> return addv(self.data, other)
>
> >>> addv
> <class __console__.addv at 10486e0>
> >>> x=addv.add
> >>> x
> <unbound method addv.add>
> >>> x(3,4)
> Traceback (innermost last):
> File "<pyshell#4>", line 1, in ?
> x(3,4)
> TypeError: unbound method must be called with class instance 1st argument
> >>>
A few comments come to mind:
- You put these functions in a class, but it seems you only need one such
list. A class may not be necessary.
- To use a class, you have to make an instance of the class: inst = addv().
You can then call inst.add(name, value) to it.
- You define __add__, which is used to add ('+') instances to other instances.
It doesn't look like it does what you think it does.
- You use the empty list as default in the __init__ def, this is a little
trap: all instances will share the same list, probably not what you want.
- A dictionary would probably be the best place to store (name, value)
pairs, since you can do lookups on names quickly.
An improved class implementation looks like this:
class addv:
def __init__(self):
self.data = []
def add(self, name, value):
self.data.append((name, value))
inst = addv()
inst.add('shaun', 20)
print inst.data
With functions that would simply become:
data = []
def add(name, value):
data.append((name, value))
add('shaun', 20)
print data
With a dictionary:
data = {}
def add(name, value):
data[name] = value
add('shaun', 20)
print data
print data['shaun']
print data.items()
--
Remco Gerlich, scarblac at pino.selwerd.nl
This is no way to be
Man ought to be free -- Ted Bundy
That man should be me
More information about the Python-list
mailing list