0

I have below code:

arg = object()
arg.abc = "abc_text"
print arg.abc

It throws error "AttributeError: 'object' object has no attribute 'abc'"

But When the code is modified to below, it works:

class MyCustomClass(object):
    pass

arg = MyCustomClass()
arg.abc = "abc_text"
print arg.abc

What happened exactly I didn't understand at all. object is base for and class and I tried to set attribute. It should have worked. But it didn't. And what exactly happened when a custom class is called?

tdka
  • 86
  • 1
  • 5
  • 2
    *"It should have worked"* - no, it shouldn't, that's why it didn't. Possible duplicate of http://stackoverflow.com/q/1529002/3001761 – jonrsharpe Jun 15 '16 at 15:16
  • This is a very interesting question. I'm glad you asked it (even if it was only to bring the dupe to my attention). – mgilson Jun 15 '16 at 15:27
  • Ya, saw the other link. It's the same he asked. Didn't see it before! But I am not even clear with the ans over there. @mgilson , If you could ans it in a line or 2 in the comments here, would be helpful to me :) – tdka Jun 15 '16 at 15:35
  • @tdka -- The point is that to add an attribute to something, it needs to have a `__dict__` (to store the attributes in). Instances of `object` don't have a `__dict__` (to save on memory) so you can't add attributes to instances of `object`. Brushing aside the subtleties of `__slots__`, instances of `object` subclasses _do_ have a `__dict__` so you _can_add attributes. – mgilson Jun 15 '16 at 15:40
  • @mgilson -- ya got it. Thanks. In addition to it, wanted to ask 1 more question. Is the base object immutable. can't we change any of its attributes? – tdka Jun 15 '16 at 15:44
  • @tdka -- The base object is a type ... and it looks like trying to set attributes on it lead to an explicit `TypeError`. So that looks like it's explicitly disallowed (though I can't think of any reason why you would _want_ to do that :-) – mgilson Jun 15 '16 at 15:54
  • @mgilson -- Thanks :) I actually had 15 attributes and wanted to set in a single object before passing into a different method. Hence the situation arrised and wanted to do this :) – tdka Jun 15 '16 at 16:22
  • If you are using a recent enough python version, `types.SimpleNamespace` should do the trick (IIRC). – mgilson Jun 15 '16 at 16:36
  • Using 2.7 in the project. – tdka Jun 16 '16 at 04:50

0 Answers0