object() can't have attributes

Irmen de Jong irmen.NOSPAM at xs4all.nl
Wed Dec 23 10:49:33 EST 2015


On 23-12-2015 13:58, Chris Angelico wrote:
> On Wed, Dec 23, 2015 at 11:46 PM, Neal Becker <ndbecker2 at gmail.com> wrote:
>> Sometimes I want to collect attributes on an object. Usually I would make
>> an empty class for this. But it seems unnecessarily verbose to do this. So
>> I thought, why not just use an Object? But no, an instance of Object
>> apparantly can't have an attribute. Is this intentional?
>> Yes; there are other uses of object() that benefit from being
> extremely compact. You can use types.SimpleNamespace for this job, or
> you can create the empty class as you're describing. (Chances are you
> can give the class a meaningful name anyway.)
>> ChrisA
>
Hey, nice, didn't know about SimpleNamespace. I was about to suggest
collections.namedtuple but that one is probably more than Neal asked for.
Alternatively, you can still put attributes on a function, so this works as well (but I
think it's rather ugly):
thing = lambda: None
thing.attr = 42
vars(thing) # {'attr': 42}
-irmen


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /