0

I do the following assignment (File is a class):

file_object = File()
file_object.file_type = file_type

and I get:

AttributeError: 'File' object has no attribute 'file_type'

How can it be?

I thought, that you could add attributes dynamically (and it worked always before).

I've upgraded my python to 2.7.13, and now I have this problem.

File (in my case) has __dict__ and does not have __slot__:

>>> print dir(File)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'factory', 'method_name']
Igor Chubin
  • 51,940
  • 8
  • 108
  • 128

2 Answers2

0

Possibly, lack of a __dict__ in your class, prevents dynamically adding an attribute. See answer https://stackoverflow.com/a/1285287/2707864

Your class may have the __slots__ special attribute, preventing addition of __dict__. See answer https://stackoverflow.com/a/1529099/2707864

Check other possibly useful questions/answers:

Why is adding attributes to an already instantiated object allowed?

How to add property to a class dynamically? (marginal)

  • A good idea, but no. I've added `dir(File)` output to the question. And as I said already: it happened after python upgrade – Igor Chubin Jul 26 '17 at 08:35
0

I think that your code is reading File() as an object, not a class - https://docs.python.org/2.4/lib/bltin-file-objects.html.

PythonParka
  • 114
  • 1
  • 11