Newbie OOP Question & Code Snippet

Joshua Landau joshua.landau.ws at gmail.com
Wed Dec 21 14:38:11 EST 2011


On 21 December 2011 19:12, Dean Richardson P.Eng <dean at red-spanner.com>wrote:

> Hi All,
> I'm a newbie just learning Python, using a couple of books to learn the
> language. (Books: "Visual Quickstart Guide - Python, 2nd Ed", "Practical
> Programming - An Intro to Computer Science using Python"). I'm just now
> learning OOP material as presented in both books -- I'm new to this
> approach -- the last formal language I learned was Fortran77 -- :o)  I am
> running Python 3.2.1 on Mac OS/X 10.6.8.
>
> My problem stems from a simple example in the Visual Quickstart book. The
> code is:
> ----------------------------
> #person.py
> class Person:
>     """Class to represent a person"""
>     def __init__(self):
>         self.name=' '
>         self.age=0
>     def display(self):
>         print("Person('%s', age)" %
>               (self.name, self.age))
>

The "% (self.name, self.age)" means that two arguments are given in. You
only have one "%s" in the string (untested, so I may be completely off).

Additionally, use str.format now:
"Person({}, {})".format(self.name, self.age)


>  -------------------------
>  When I run this, the shell presents thus:
> >>> ================================ RESTART
> ================================
> >>>
> >>> p=Person()
> >>> p.name='Bob'
> >>> p.age=24
> >>> p.display()
> Traceback (most recent call last):
>   File "<pyshell#33>", line 1, in <module>
>     p.display()
>   File "/Volumes/dean_richardson/GoFlex Home Personal/Dean's
> Code/Python3.x/Person.py", line 9, in display
>     (self.name, self.age))
> TypeError: not all arguments converted during string formatting
> >>>
> ---------------
> I'm sure this is something simple, but I can't see it. Any help
> appreciated!
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20111221/c2be91a7/attachment.html>


More information about the Python-list mailing list