4

What's wrong with the last three lines?

class FooClass(object):
    pass 
bar1 = object() 
bar2 = object() 
bar3 = object() 
foo1 = FooClass() 
foo2 = FooClass() 
foo3 = FooClass() 
object.__setattr__(foo1,'attribute','Hi')
foo2.__setattr__('attribute','Hi')
foo3.attribute = 'Hi'
object.__setattr__(bar1,'attribute','Hi')
bar2.attribute = 'Hi'
bar3.attribute = 'Hi'

I need an object having a single attribute (like foo) should I define a class (like FooClass) just for it?

2 Answers 2

4

object is built-in type, so you can't override attributes and methods of its instances.

Maybe you just want a dictionary or collections.NamedTuples:

>>> d = dict(foo=42)
{'foo': 42}
>>> d["foo"]
42

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'], verbose=True)
>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
>>> p[0] + p[1]             # indexable like the plain tuple (11, 22) 33
>>> x, y = p                # unpack like a regular tuple
>>> x, y (11, 22)
>>> p.x + p.y               # fields also accessible by name 33
>>> p                       # readable __repr__ with a name=value style Point(x=11, y=22)
Sign up to request clarification or add additional context in comments.

1 Comment

l = list(); l.attr = 7; AttributeError... I guess you're right!
1

You cannot add new attributes to an object(), only to subclasses.

Try collections.NamedTuples.

Besides, instead of object.__setattr__(foo1,'attribute','Hi'), setattr(foo1, 'attribute', 'Hi') would be better.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.