object instance after if isalpha()

  • Thread starter Marcelo Urbano Lima
  • Start date
M

Marcelo Urbano Lima

Hi
I'm still learning python and I've been loving it, but, that's not the
reason I'm writing.

I'm trying to create an object only if a variable is alpha and see what I
get.

$ cat 1.py
class abc:
def __init__(self):
name='marcelo'

a='STRING'
print a.isalpha()

if a.isalpha():
x=abc()

print 'was x created?:', x,'\n'
print x.name


$ python 1.py
True
was x created?: <__main__.abc instance at 0x186b9e6c>

Traceback (most recent call last):
File "1.py", line 12, in ?
print x.name
AttributeError: abc instance has no attribute 'name'

Why? (I really think I'm doing something stupid but could not see)
btw, it's python 2.4.1 for cygwin.

I'd really appreciate your help.

Thanks

_________________________________________________________________
Seja um dos primeiros a testar o Windows Live Messenger Beta a geração do
seu MSN Messenger.
http://imagine-msn.com/minisites/messenger/default.aspx?locale=pt-br
 
B

Ben Cartwright

Marcelo said:
class abc:
def __init__(self):
name='marcelo'
print x.name
Traceback (most recent call last):
File "1.py", line 12, in ?
print x.name
AttributeError: abc instance has no attribute 'name'

In Python, you explicitly include a reference to an object when setting
or accessing the object's attributes... even when you're inside one of
that objects methods. I.e.:

class abc:
def __init__(self):
self.name='marcelo'

When you omit the "self." bit, Python creates a variable local to
__init__() named "name", and the attribute is never set. This is
different from some other OO languages (e.g. C++/Java/C#'s "this"), may
take some getting used to.

Hope that helps,
--Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top