André Puel
André Puel

Reputation: 9219

Is it possible to create attributes out of the class scope?

Is it possible to add attributes to a object outside of its scope?

I.e: The following code doesnt works, how do I do what I intended to do with that code?

b = object()
b.foo = "bar"

Upvotes: 3

Views: 81

Answers (2)

jathanism
jathanism

Reputation: 33724

Instances of object() are "featureless" by design in that they do not have any magic methods (no dict, no getters/setters, no iteration, etc.) to dictate default behaviors you might expect from other types. In order for it to work you must subclass object first:

class Foo(object): pass
f = Foo()
f.bar = "omgwtf!"

Upvotes: 5

Jeremy Banks
Jeremy Banks

Reputation: 129756

In general, it is possible. However, it is not possible for most types that are implemented in C, instead of in Python. Unfortunately, this applies to the most often-used of the standard Python interpreter's built-in types.

If you define a class of your own in Python, you'll see that it works fine.

class MyObject(object):
    pass

b = MyObject()
b.foo = "bar"

Upvotes: 5

Related Questions