Beginner Help - class problem or string copy semantics?

William Tanksley wtanksle at dolphin.openprojects.net
Mon Apr 19 18:11:59 EDT 1999


On Mon, 19 Apr 1999 21:47:47 GMT, cmedcoff at my-dejanews.com wrote:
>As will soon be apparent I am totally new to Python. In the code fragment
>below I expect to see the output "foobar", but I do not.  Can anyone tell me
>why? All the bookstores seem to be out of "Learning Python".  Are they out of
>print already or has the initial shipment still not released?

I suspect that the store hasn't ordered any.  Keep bugging them :).

>class Test:
>    _name = ""
>    def __init__(self, name):
>        _name = name
>    def show(self):
>        print self._name

First of all, I suspect that you're using the underscore because you want
the variable to be private.  If so, try a double underscore, like __name.

>mytest = Test("foobar")
>mytest.show()

The problem is that you're setting "_name" (a variable local to the
__init__ function) instead of "self._name".  Add that "self." and you'll
be fine.

Also, you don't need to have a class variable named the same as your
object variable -- it'll never get viewed.  Feel free to remove the '_name
= ""' line from the class definition.

>Regards,
>Chuck

-- 
-William "Billy" Tanksley
"But you shall not escape my iambics."
           -- Gaius Valerius Catullus




More information about the Python-list mailing list