Help with Dictionaries and Classes requested please.
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Aug 9 06:50:50 EDT 2007
special_dragonfly a écrit :
(snip)
> I've managed to solve the problem, I really was just being a dunce. Here's
> how incase anyone is wondering:
>
> class MyClass:
> def __init__(self):
> name=""
> dict={}
> dict[0]=[]
> dict[0].append(MyClass())
> dict[0][0].name="Hello"
> print dict[0][0].name
>
> I'm sorry if I've wasted anyones time, although if there's a better way of
> doing the above I'd still be interested to know.
# unless you need pre 2.3.x compat, better to use newstyle classes
class MyClass(object):
# use the initializer to initialize your instance
def __init__(self, name=''):
# the use of 'self' is mandatory, else you only have a local var
self.name = name
# don't use builtin names as identifiers - unless you really want to
# shadow the builtins
d = {0:[MyClass('hello')}
d[0].append(MyClass('goodbye'))
d.setdefault(1, []).append(MyClass('Yo'))
print d
HTH
More information about the Python-list
mailing list