[Tutor] set locals
Mark Lawrence
breamoreboy at yahoo.co.uk
Wed Dec 18 18:45:02 CET 2013
On 18/12/2013 11:16, spir wrote:
> On 12/18/2013 12:07 PM, eryksun wrote:
>> On Wed, Dec 18, 2013 at 5:40 AM, spir <denis.spir at gmail.com> wrote:
>>> C.__setattr__(C, "baz", "BAZ")
>>> which fails, for any reason, with
>>> TypeError: can't apply this __setattr__ to type object
>>
>> You need __setattr__ from the metaclass:
>>
>> >>> class C: pass
>> ...
>> >>> type(C).__setattr__(C, "baz", "BAZ")
>> >>> C.baz
>> 'BAZ'
>
> Oh, that makes sense: so, __setattr__ on a class is for its instances,
> right? (thus, to set attrs on a class itself, we need ___setattr__ from
> its own class, if I understand rightly?)
>
>> You can bind the method like this:
>>
>> >>> C_setattr = type(C).__setattr__.__get__(C)
>> >>> C_setattr('foo', 'bar')
>> >>> C.foo
>> 'bar'
>>
>> But just use built-in setattr(), really.
>
> Really, yes!
>
> Denis
>
Can I be so bold as to ask how discussing metaclasses and __setattr__ on
a tutor mailing list is going to help the newbie who's having problems
with their "hello world" program?
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list