how to use variable to substitute class's variable?
Hans
hansyin at gmail.com
Thu Mar 17 20:31:46 EDT 2011
On Mar 17, 12:47 am, Benjamin Kaplan <benjamin.kap... at case.edu> wrote:
> On Thu, Mar 17, 2011 at 3:31 AM, Hans <hans... at gmail.com> wrote:
> > I have things like:
> > file1:
> > class aaa:
> > def __init__(self):
> > self.variable1='a1'
> > self.variable2='a2'
> > self.varable3='a3'
>
> > in main proc:
> > import file1
> > b=file1.aaa()
> > c={'variable1':'value1','variable2':'value2','variable3':'value3'}
> > for key in c:
> > b.key=c[key] >>>>>>>>>>>Problem is here!!!
>
> > I hope put value1 to b.variable1, value2 to b.variable2 and value3 to
> > b.variable3. it does not work. How can I do it?
>
> b.key gets the "key" attribute of b, not the attribute that has the
> same name as the variable called key. Otherwise, you'd have to
> reference it as b."key" normally. If you want to dynamically set the
> variable, you'll have to use the setattr function
>
> setattr(b, key, c[key])
>
>
>
> > By the way, I know dictionary can bind two variable together, like a 2-
> > dimension array. but, if I need group 3 or more variables together,
> > (each group has 3 or more variables)like a 3-dimension(or higher)
> > array, Is there an easy way besides "class"?
>
> A dictionary does not bind two variables together. A dictionary is a
> hash map- it maps keys to values. Each key will map to exactly one
> value. If you want to store a list of associated values, use a tuple.
> A tuple is an immutable collection of objects (the tuple itself is
> immutable, not necessarily the objects in it). It can be indexed just
> like a list.
>
>
>
> >>> l = [(0,0), (0,1,2,3,4,5,6,7), (0,1,'foo', 5 ,6)]
> >>> l[0]
> (0, 0)
> >>> l[2]
> (0, 1, 'foo', 5, 6)
> >>> l[2][1]- Hide quoted text -
>
> - Show quoted text -- Hide quoted text -
>
> - Show quoted text -
Thank you VERY MUCH! it works.
More information about the Python-list
mailing list