470,815 Members | 1,293 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,815 developers. It's quick & easy.

object instance after if isalpha()

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/mes...x?locale=pt-br

Apr 13 '06 #1
1 2945
Marcelo Urbano Lima wrote:
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

Apr 13 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Ryan Mitchley | last post: by
2 posts views Thread by Matt | last post: by
4 posts views Thread by Luke Matuszewski | last post: by
12 posts views Thread by Andrew Poulos | last post: by
3 posts views Thread by nuno | last post: by
reply views Thread by mihailmihai484 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.