Mailing List Archive

Beginner Help - class problem or string copy semantics?
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?

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


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

Regards,
Chuck

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/ Search, Read, Discuss, or Start Your Own
Beginner Help - class problem or string copy semantics? [ In reply to ]
On Mon, 19 Apr 1999 21:47:47 GMT, cmedcoff@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
Beginner Help - class problem or string copy semantics? [ In reply to ]
cmedcoff@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?
...
> class Test:
> _name = ""
> def __init__(self, name):
> _name = name
> def show(self):
> print self._name
>
> mytest = Test("foobar")
> mytest.show()

The line "_name = name" should be "self._name = name".
Unlike C++, Python does not supply an implicit "this" or "self".
(Once you get used to it, this is actually a good thing.)
The "_name" you assigned to is simply a local variable within
the __init__() method; it vanishes as soon as the method ends.