setattr() on "object" instance

S

Sean DiZazzo

Why is it that you can setattr() on an instance of a class that
inherits from "object", but you can't on an instance of "object"
itself?
Traceback (most recent call last):
1000

I notice that the first example's instance doesn't have a __dict__.
Is the second way the idiom?

~Sean
 
A

Ahmad Syukri b

Why is it that you can setattr() on an instance of a class that
inherits from "object", but you can't on an instance of "object"
itself?


Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'x'

I suppose you cannot set attributes to instances of any built-in
classes, i.e. int(), list() etc.
1000

I notice that the first example's instance doesn't have a __dict__.
Is the second way the idiom?

~Sean

Since all classes inherit from object, I suppose the definition can be
as simple as 'class Object:pass', and assignment can be as simple as
'o.x = 1000'

A. Syukri
 
R

R. David Murray

Sean DiZazzo said:
Why is it that you can setattr() on an instance of a class that
inherits from "object", but you can't on an instance of "object"
itself?

Traceback (most recent call last):

1000

I notice that the first example's instance doesn't have a __dict__.
Is the second way the idiom?

The lack of a __dict__ is why you can't set the attribute.
I've occasionally wanted to use instances of object as holders of
arbitrary attributes and wondered why I couldn't (from a language design
perspective). But that was only for testing. In real code I think I'd
always want a fully defined class.
 
A

Aahz

Why is it that you can setattr() on an instance of a class that
inherits from "object", but you can't on an instance of "object"
itself?

Traceback (most recent call last):

1000

I notice that the first example's instance doesn't have a __dict__.
Is the second way the idiom?
.... __slots__ = []
.... Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'C' object has no attribute 'foo'
--
Aahz ([email protected]) <*> http://www.pythoncraft.com/

"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :)"
--Michael Foord paraphrases Christian Muirhead on python-dev, 2009-3-22
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,216
Latest member
topweb3twitterchannels

Latest Threads

Top