Newbie OOP Question & Code Snippet

MRAB python at mrabarnett.plus.com
Wed Dec 21 14:31:05 EST 2011


On 21/12/2011 19:12, Dean Richardson P.Eng 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))
>   -------------------------
>   When I run this, the shell presents thus:
>  >>> ================================ RESTART
> ================================
>  >>>
>  >>> p=Person()
>  >>> p.name <http://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 <http://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!
>
It should be:

print("Person('%s', %s)" % (self.name, self.age))

As it is, you're giving it 2 values but only %s placeholder.



More information about the Python-list mailing list