Beginner's (?) Question: Attributes and __dict__

13 views
Skip to first unread message

Richard Höchenberger

unread,
May 11, 2016, 10:31:42 AM5/11/16
to psychopy-dev
Hello, I've been looking through some code in psychopy.visual
recently; and on several occasions, I would find something like:

----------
class MyClass(ParentClass):
def __init__(self, attribute=None):
self.__dict__['attribute'] = attribute
----------

I don't understand the rationale for this; could one not simply
achieve the exact same attribute assignment via:

----------
class MyClass(ParentClass):
def __init__(self, attribute=None):
self.attribute = attribute
----------

? Why use self.__dict__ instead?

I'm sorry if this is a trivial question, but I've simply been unable
to get my head around it.

Thanks for your help,

Richard

Jonathan Peirce

unread,
May 11, 2016, 10:43:48 AM5/11/16
to psycho...@googlegroups.com
That gets done on occasion for objects that have property setter methods
and setting the __dict__ value avoids the setter being called. Avoiding
using the setter is sometimes handy if:
- we want to avoid the extra jobs that the property setter performs
(e.g. if it will upload a texture to the graphics card and we know we'll
have to do that again a few lines later we could avoid it happening the
first time)
- we can't be sure that all the other variables are set up yet for
that parameter to do all its work

Jon
--
Jonathan Peirce
University of Nottingham

http://www.peirce.org.uk





This message and any attachment are intended solely for the addressee
and may contain confidential information. If you have received this
message in error, please send it back to me, and immediately delete it.

Please do not use, copy or disclose the information contained in this
message or in any attachment. Any views or opinions expressed by the
author of this email do not necessarily reflect the views of the
University of Nottingham.

This message has been checked for viruses but the contents of an
attachment may still contain software viruses which could damage your
computer system, you are advised to perform your own checks. Email
communications with the University of Nottingham may be monitored as
permitted by UK legislation.

Richard Höchenberger

unread,
May 11, 2016, 10:49:40 AM5/11/16
to psychopy-dev
Great, thank you very much, this was a really helpful explanation!

All the best,

Richard
Reply all
Reply to author
Forward
0 new messages