[Tutor] Simple Question On A Method (in subclass)

Alan Gauld alan.gauld at btinternet.com
Mon Oct 24 02:28:10 CEST 2011


On 24/10/11 00:54, Chris Kavanagh wrote:

>> Speaking of the last line of code, I have a question about that also.
>> The last line should have been (without my error) {member.tell()}.
>> My question is, why couldn't this last line have been {print member}??

It could have been, but the output would have been different.
When you call print it automatically calls the str() function on the 
arguments. So {print member} would actually print out
{str(member)}. But str(member) is a message to say that member is an 
instance of a class, not a list of the attributes formatted in a 
specific way.

Now Swaroop could have chosen to implement a __str__() method in the 
classes in which case print would have done what you expect. (But I 
guess he felt that would be too advanced at this stage in his tutor)
Another option would have been to make tell() return a string rather 
than print it, in which case you could have used {print member.tell()}

>> Every example of an iterator I've seen until this point of my learning,
>> has had a print statement then the item variable.

Thats just a coincidence with how you've seen iterators used. An 
iterator allows you to do anything you like to the items being iterated 
over. It just so happens that so far you have only seen them being 
printed. Printing is only one, and is far from the most common, use of 
iterators.

>> the item variable to call the function {tell()}. This is sorta confusing
>> to me. What if there was no function to print out the Student and
>> Teacher variable??

You would have to rely on the str() conversion - which will always print 
something, even if its not very helpful! Or, you could manually print 
the contents of the member - but that gets very complicated where you 
have mixed sub and superclasses in a single collection.

 > How would the iterator been printed out in that
> case??

Being picky, you are not printing the iterator, you are printing the 
items returned by the iterator. But ignoring that, you would do one of 
the options I described above:

1) print the object using its built in str() convertion
2) create your own string conversion method (__str__() )
3) print the individual data members by hand

Personally I would choose the second one, but modifying the code is not 
always possible, in which case, option 3 wins. Option 1 is usually 
pretty useless!

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list