[Tutor] What I do wrong
class MyList (): def __init__(self, value): self.value = [] for x in value: self.value.append(x) def __add__(self , other): return MyList(self.value+other) def __mul__(self , other): return MyList(self.value*other) def __getitem__(self , item): return MyList(self.value+item) def __len__(self ): return len(self.value) def __getlice__(self , low, high): return MyList(self.value[low:high] def append(self , other): self.list=self.list.append(other) return self.list def __getattr__(self , name): return getattr(self.value, name) def __repr__(self ): return 'self.value' -- Grigor Kolev ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What I do wrong
What doesn't work, does it have errors, etc.! On Sun, Dec 13, 2009 at 12:25 PM, Grigor Kolev wrote: > class MyList (): >def __init__(self, value): >self.value = [] >for x in value: >self.value.append(x) >def __add__(self , other): >return MyList(self.value+other) >def __mul__(self , other): >return MyList(self.value*other) >def __getitem__(self , item): >return MyList(self.value+item) >def __len__(self ): >return len(self.value) >def __getlice__(self , low, high): >return MyList(self.value[low:high] >def append(self , other): >self.list=self.list.append(other) >return self.list >def __getattr__(self , name): >return getattr(self.value, name) >def __repr__(self ): >return 'self.value' > -- > Grigor Kolev > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Learning Python
It is from book Learning Python Operator overloading. Write a class called Mylist that shadows (“wraps”) a Python list: it should overload most list operators and operations, including +, indexing, iteration, slicing, and list methods such as append and sort. See the Python reference manual for a list of all possible methods to support. Also, provide a con- structor for your class that takes an existing list (or a Mylist instance) and copies its components into an instance member. Experiment with your class interac- tively. Things to explore: a. Why is copying the initial value important here? b. Can you use an empty slice (e.g., start[:]) to copy the initial value if it’s a Mylist instance? c. Is there a general way to route list method calls to the wrapped list? d. Can you add a Mylist and a regular list? How about a list and a Mylist instance? e. What type of object should operations like + and slicing return? What about indexing operations? f. If you are working with a more recent Python release (version 2.2 or later), you may implement this sort of wrapper class by embedding a real list in a standalone class, or by extending the built-in list type with a subclass. Which is easier, and why? My answer is: class MyList (): def __init__(self, value=[]): self.list=[] for i in value: self.list.append(i) def __add__(self , other): return self.list def __mul__(self , other): return self .list def __delitem__(self , other): return self .list def __geritem__(self , other): return self.list def __repeat__(self , other): return self.list def sort(self ): self.list = self.list.sort() return self.list def append(self , other): self.list=self.list.append(other) return self.list This is work -- In the book answer is this: class MyList: def _ _init_ _(self, start): #self.wrapped = start[:] # Copy start: no side effects self.wrapped = []# Make sure it's a list here for x in start: self.wrapped.append(x) def _ _add_ _(self, other): return MyList(self.wrapped + other) def _ _mul_ _(self, time): return MyList(self.wrapped * time) def _ _getitem_ _(self, offset): return self.wrapped[offset] def _ _len_ _(self): return len(self.wrapped) def _ _getslice_ _(self, low, high): return MyList(self.wrapped[low:high]) def append(self, node): self.wrapped.append(node) def _ _getattr_ _(self, name): # Other members: sort/reverse/etc return getattr(self.wrapped, name) def _ _repr_ _(self): return repr(self.wrapped) Answer in the book does not work Where is the error -- Grigor Kolev ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Learning Python
"Grigor Kolev" wrote My answer is: class MyList (): def __init__(self, value=[]): self.list=[] for i in value: self.list.append(i) def __add__(self , other): return self.list def __mul__(self , other): return self .list def __delitem__(self , other): return self .list def __geritem__(self , other): return self.list def __repeat__(self , other): return self.list def sort(self ): self.list = self.list.sort() return self.list def append(self , other): self.list=self.list.append(other) return self.list This is work Given that add does not add anything how do you define "work"? Do you mean it executes without error messages? -- In the book answer is this: class MyList: def _ _init_ _(self, start): #self.wrapped = start[:] # Copy start: no side effects self.wrapped = []# Make sure it's a list here for x in start: self.wrapped.append(x) def _ _add_ _(self, other): return MyList(self.wrapped + other) def _ _mul_ _(self, time): return MyList(self.wrapped * time) def _ _getitem_ _(self, offset): return self.wrapped[offset] def _ _len_ _(self): return len(self.wrapped) def _ _getslice_ _(self, low, high): return MyList(self.wrapped[low:high]) def append(self, node): self.wrapped.append(node) def _ _getattr_ _(self, name): # Other members: sort/reverse/etc return getattr(self.wrapped, name) def _ _repr_ _(self): return repr(self.wrapped) Answer in the book does not work Where is the error What error do you get? These merthods do entirely different things to yours. But without an error description its hard to comment, I don't feel like reading through line buy line trying to guess what the problem might be. It will also help if you tell us which version of Python you are using and which Operating System. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Learning Python
On 12/13/2009 4:36 AM Grigor Kolev said... Your __init__ looks OK. All the other methods return either self.list or (with sort and append) return None because you've reassigned self.list to the return value of self.list.sort() and self.list.append()(both sort and append methods change the object in place and return None -- which you've then assigned to self.list) I've added comment lines below that describe what I would expect each method to do. You'll need to write python code to perform each description. I've completed one to get you started. I'd advise you to revisit the tutorial and refresh your working knowledge of core python. Magic methods might a bit advanced. Emile My answer is: class MyList (): def __init__(self, value=[]): self.list=[] for i in value: self.list.append(i) def __add__(self , other): # add other to self.list # return self.list += other return self.list def __mul__(self , other): # return the result of multiplying self.list by other return self .list def __delitem__(self , other): # delete item other from self.list return self .list def __geritem__(self , other): # return self.list's other item return self.list def __repeat__(self , other): # ?? maybe repr? return self.list def sort(self ): # sort self.list in place self.list = self.list.sort() return self.list def append(self , other): # append item other to self.list self.list=self.list.append(other) return self.list ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Learning Python
Hi, Kent Johnson wrote: > Python in a Nutshell is good if you want a compressed but readable > introduction. I am thinking of buying this one, but the topical 2nd edition is from 2006. Does anyone know if a new version, covering Python 3, is coming to market soonish? David ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Read-create-edit file
Hi list, I finally manage to sort of complete my read-create-edit.py file (after finding precious free time). I appreciate your review and good/bad comments to my code. It look and runs ok from my side here :-) #read_create_edit.py #!/usr/bin/env python # -*- coding: utf-8 -*- ''' Exercise 3.12: combined read, edit and write program use import to utilize codes from other module files Core Python Programming 2nd Edition by Wesley Chun Filename: read_create_edit.py Created: 13-Dec-2009 ''' from readFile import main as read_main from readFile import repeat from createFile1 import main as create_main from appendFile import main as edit_main def main(): '''heart of the program''' while True: print ''' (1) read file (2) create file (3) edit file (add data) (4) quit program ''' try: ask = int(raw_input('choose your option: ')) if ask == 1: read_main() elif ask == 2: create_main() elif ask == 3: edit_main() elif ask == 4: break else: print 'invalid choice: enter (1), (2), (3) or (4) only!' except Exception, e: print 'Error detected: ', e if __name__ == '__main__': main() ask = repeat() if ask == 'y': main() else: print 'thank you for using python, goodbye!!' #appendFile.py #!/usr/bin/env python # -*- coding: utf-8 -*- ''' Chapter 3.1 : Core Python Programming 2nd Edition by Wesley Chun Filename: appendFile.py Created: 09-Dec-2009 v1.0: append user input to existing file ''' import os, sys def main(): while True: fname = raw_input('Enter filename to APPEND/edit: ') if os.path.isdir(fname): print('%s is a directory!') % fname elif not os.path.exists(fname): print 'this is APPEND mode; select CREATE to create new file' elif fname.isspace(): print 'Space is not allowed' else: #os.path.exists(fname): #found candidate to edit break all = [] # container list to hold user input lines print("file '%s' will be appended by your input\n") % fname quit_prompt = "[start your input to quit enter 1 dot]--> " while True: entry = raw_input(quit_prompt) if entry == '.': break else: all.append(entry) confirm = raw_input('save file to disk?(y/N)') confirm = confirm.lower() #convert to lowercase if confirm == 'y': fobj = open(fname, 'a') fobj.write('\n'.join(all) + '\n') #(a) fobj.close() print('DONE! open %s to view your file') % fname else: print 'not saving to disk!' if __name__ == '__main__': main() #(a) as per help from tutor list #readFile.py #!/usr/bin/env python # -*- coding: utf-8 -*- ''' Exercise 3.10b: read text file line by line; raise error if file not found, encapsulate program body with main function for code re-use Core Python Programming 2nd Edition by Wesley Chun Filename: readFile.py Created: 01-Dec-2009 edited: 07-Dec-2009 Version1: replace try-except with os.path.exists() ''' import os def repeat(): '''ask to repeat or no''' ask = raw_input('\ntry again? [N/y]') ask = ask.lower() return ask def main(): while True: fname = raw_input('enter file name to READ: ') if os.path.isdir(fname): print('%s is a directory!') % fname elif not os.path.exists(fname): print 'Error: file not found!' else: fobj = open(fname, 'r') for eachline in fobj: print eachline, fobj.close() break if __name__ == '__main__': main() #createFile.py #!/usr/bin/env python # -*- coding: utf-8 -*- ''' Chapter 3.1 : create a file and write to disk Core Python Programming 2nd Edition by Wesley Chun Filename: createFile1.py Created: 07-Dec-2009 rev. 1: fine tune script by checking if input name exist, is a file or a directory ''' import os, sys def main(): while True: fname = raw_input('Enter filename to CREATE: ') if os.path.isdir(fname): print('%s is a directory!') % fname elif os.path.exists(fname): print '%s already exist' % fname elif fname.isspace(): print 'Space is not allowed' else: break all = [] # container list to hold user input lines print("\nPopulate your file *%s*! \n") % fname quit_prompt = "[to quit enter a dot '.' by itself]--> " while True: entry = raw_input(quit_prompt) if entry == '.': break else: all.append(entry) confirm = raw_input('save file to disk?(y/N)') confirm = confirm.lower() #convert to lowercase if confirm == 'y': fobj = open(fname, 'w') fobj.write('\n'.join(all)) fobj.close() print('DONE! open %s to view your file') % fname else: print 'not saving to disk!' if __name__ == '__main__': main() -- Regards, bibs M. Host/Kernel/OS "cc02695" running Linux 2.6.31-5.slh.4-sidux-686 [sidux 2009-02 Αιθήρ - kde-full - (200907141427) ] www.sidux.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Read-create-edit file
2009/12/13 biboy mendz : > Hi list, > > I finally manage to sort of complete my read-create-edit.py file (after > finding precious free time). I appreciate your review and good/bad comments > to my code. It look and runs ok from my side here :-) > > -- > Regards, > bibs M. > > Host/Kernel/OS "cc02695" running Linux 2.6.31-5.slh.4-sidux-686 [sidux > 2009-02 Αιθήρ - kde-full - (200907141427) ] > www.sidux.com > > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > First of all it's too long to paste into an email, especially if you'rte using a client that strips leading whitespace. Paste it into a pastebin. I personally prefer python.codepad.org, as it lets you test code on the server, unless it depends on third party modules. Uplaod it to a pastebin, send us the link, and we might consider taking a look. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Read-create-edit file
On Mon, Dec 14, 2009 at 1:17 AM, Rich Lovely wrote: > > First of all it's too long to paste into an email, especially if > you'rte using a client that strips leading whitespace. Paste it into > a pastebin. I personally prefer python.codepad.org, as it lets you > test code on the server, unless it depends on third party modules. > > Uplaod it to a pastebin, send us the link, and we might consider taking a > look. > > > > Yes my bad, found out too late all > -- > Rich "Roadie Rich" Lovely > > There are 10 types of people in the world: those who know binary, > those who do not, and those who are off by one. > -- Best Regards, bibimidi ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Read-create-edit file
On Mon, Dec 14, 2009 at 6:09 AM, bibi midi wrote: > > > On Mon, Dec 14, 2009 at 1:17 AM, Rich Lovely wrote: > >> >> First of all it's too long to paste into an email, especially if >> you'rte using a client that strips leading whitespace. Paste it into >> a pastebin. I personally prefer python.codepad.org, as it lets you >> test code on the server, unless it depends on third party modules. >> >> Uplaod it to a pastebin, send us the link, and we might consider taking a >> look. >> >> >> >> Yes my bad, found out too late. Sorry for that. Will post in pastebin or equal and give the link. -- Best Regards, bibimidi Sent from Riyadh, 01, Saudi Arabia ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Read-create-edit file
Here's the link: http://paste.debian.net/53933/ On Mon, Dec 14, 2009 at 6:10 AM, bibi midi wrote: > > > Yes my bad, found out too late. Sorry for that. Will post in pastebin or > equal and give the link. > > > -- > Best Regards, > bibimidi > > -- Best Regards, bibimidi ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor