why can't python detect certain instance variables

This is the place for queries that don't fit in any of the other categories.

why can't python detect certain instance variables

Postby pythonnoob123 » Sun Jul 14, 2013 10:43 am

What I mean by that question is say you have this piece of code

Code: Select all
class test(object):
   def __init__(self,x):
      self.x=x
      a=0

you then create an instance and it detects x
Code: Select all
>>> b=test(3)
>>> b.x
3


but when I call b.a, it claims that my object has no such attribute. But if I switch the order in which self.x=x and a=0 are written in the __Init__ function, the code works perfectly. Any particular reason why?
pythonnoob123
 
Posts: 4
Joined: Mon Jul 08, 2013 11:29 am

Re: why can't python detect certain instance variables

Postby Mekire » Sun Jul 14, 2013 10:51 am

You never made a an instance variable. It is just some variable local to your init method.
Don't forget your self:
Code: Select all
class test(object):
   def __init__(self,x):
      self.x=x
      self.a=0

Code: Select all
>>> b = test(3)
>>> b.x
3
>>> b.a
0
>>>

-Mek
User avatar
Mekire
 
Posts: 1009
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan


Return to General Coding Help

Who is online

Users browsing this forum: W3C [Linkcheck] and 1 guest