Misunderstanding classes (newbie)

Jerry 2jerry at writeme.com
Wed Feb 23 17:35:56 EST 2000


ok ...

we need to add a class the idex slice will done by playing with getitem
function

>>>class sliced_list:
          def __init__(s,first_index=1):  #1 by default
              s.f_idx=first_index
              s.list=[]
          def __getitem__(s,idx=s.f_idx):
              return s.list[idx-s.f_idx]

then
with class lm:
>>> a=sliced_list()
>>> a.list.append(lm('paul','DUBOIS',45))
and du coup* (then)
>>>a[1].lastname
paul
>>>a[0].lastname
paul
** Right cause index will be modulo-ed :)) .. add:
>>>a.list.append(lm('david','Asher',31)
>>>a[1].lastname
paul
>>>a[2].lastname
david
>>>a[3].lastname
paul
...
use __setitem__ to update :)

jerry the foolish dracomorpheus,


sorry at spam.invalid a écrit dans le message ...
>Thanks for replying.  You've written part (b), which I was also
>able to do.  But how do I get (a) the modified UserList and (b)
>the list of class elements into a single instance?  I want
>
>   a[whatever_I_decide_is_the_start_of_the_list].lastname
>
>to return
>
>   a[0].lastname
>
>automatically, and have whatever_I_decide_is_the_start
>_of_the_list default to 1 when I create an instance of
>the class.
>
>Jerry <2jerry at writeme.com> wrote:
>> This is just a list of class elements ? no ?
>> class lm:
>>    def __init__(self, last=None,first=None,age=0):
>>        self.lastname=last
>>        self.firstname=first
>>        self.age=age
>
>> then ..
>> list_lm=[]
>> a=lm('jerome','VACHER',29)
>> list_lm.append(a)
>> list_lm.append(lm('paul','DUBOIS',45))
>> a[0].lastname='jerome'
>
>> Is that you want ?
>
>
>> sorry at spam.invalid wrote:
>>>Hi,
>>>
>>>I'm a Python newbie (and an OOP newbie) trying to
>>>construct a class that:
>>>
>>>  (a) behaves like a list but has a FORTRAN-like variable
>>>      starting index,
>>>  (b) has per-index attributes.
>>>
>>>i.e. Each element of the list has two (or more) attributes,
>>>     and, by default, the first element is at x[1].
>>>
>>>e.g. x[1].lastname, x[1].firstname, x[1].age
>>>     x[2].lastname, x[2].firstname, x[2].age
>>>
>>>I seem to be able to get each part of the solution
>>>independently (the first part by using UserList and
>>>__getitem__), but when I attempt to combine them, I
>>>clearly don't understand what I'm doing.
>>>
>>>Suggestions?
>>>
>>>Thanx.
>>>
>>>P.S. Please respond to the list.





More information about the Python-list mailing list