0

I'm using PyCharm 5.0.4 Comunity Edition and Python 2.7.

My code looks like this, in the file carInput.py:

class carInput():

    def __init__(self):
       self.string = 'hi'       

I type the following in the console:

>>> car = carInput.carInput()
>>> car
<carInput.carInput instance at 0x00000000027F3D08>
>>> car.string
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: carInput instance has no attribute 'string'

I imagined that upon instantiating the carInput object, the init-method will always be executed, and the variable string is declared. However, when I try to access the object's string variable from the console, I am told that my object has no such attribute. What is it I have misunderstood?

Magnus
  • 589
  • 8
  • 26
  • You example works, both in CPython 2.7 and pypy. Are you sure that you didn't forget to reload your module after adding the `self.string`? If you have an active interpreter and make changes to modules, the interpreter will *not* notice this. You have to explicitly tell it to, e.g. by executing `reload(carInput)`. – MisterMiyagi Mar 16 '16 at 09:05

2 Answers2

1

Try changing it to this and it will run:

class carInput:
  def __init__(self):
    self.string = 'hi'

car = carInput()

print car.string

Result:

[x@localhost 36024276]$ python car.py 
hi

The reason is how the class is being defined. My file was named car, so you'll need to run python carInput.py for yours.

the happy mamba
  • 468
  • 2
  • 6
1

Since you are using python 2.X, you need to mind the difference between new-style and old-style classes.

class OldStyle:
  pass

class NewStyle(object):
  pass

In principle, you can use both types of classes. However, new style classes should always be preferred! There is no disadvantage to using them, only advantages. Advanced code often will implicitly assume classes to be new-style!

In your case, you are actually defining an old-style class.

class carInput(): # no object inside ()
    pass
Community
  • 1
  • 1
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119