Accessing parent objects

Rick Johnson rantingrickjohnson at gmail.com
Sat Mar 24 16:31:13 EDT 2018


On Saturday, March 24, 2018 at 1:20:24 PM UTC-5, D'Arcy Cain wrote:
> I'm not even sure how to describe what I am trying to do
> which perhaps indicates that what I am trying to do is the
> wrong solution to my problem in the first place but let me
> give it a shot.  Look at the following code.
> 
> class C1(dict):
>   class C2(object):
>     def f(self):
>       return X['field']
> 
> O1 = C1()
> O1['field'] = 1
> O2 = O1.C2()
> print(O2.f())

I hope this dynamic setting of instance attributes is done
for a good reason, and not because you don't know how to do
it any other way? Also, i hope this nested class structure is
also done for a very good reason, because i consider such to
be a code smell.

> I am trying to figure out what "X" should be.  I know how
> to access the parent class but in this case I am trying to
> access the parent object.

Your poor utilization of OOP terminology is defeating you.

In every OOP object there can be zero or more "class level
variables" (aka: class attributes) and there can be zero or
more "instance level variables" (aka: instance attributes).

A class attribute can be accessed from anywhere (if you know
the class symbol and the attribute name, that is). But an
instance attribute can only be accessed in one of two
manners: from within an instance (via `self.attrname`) or
from outside an instance (using a symbol bound to the
instance, such as: `O1.field` or O1['field']). And while
there might be a way to walk down the "proverbial node tree"
and arrive at the specific instance you wish to target (a la
DHTML), such would be considered black magic, as it does not
follow the standard protocols of OOP attribute access.

My suspicion is that your attempting to solve this problem
using the wrong methodology. If you would be so kind as to
explain exactly what your are doing, perhaps someone here
could offer a better solution. Perhaps OOP is not the best
solution. Or perhaps it is? But we cannot be sure until we
know more about the general problem.

> I tried various forms of super() but that didn't seem to
> work.

Python's super (at least <= 2.x) is notoriously blinkered. I
avoid it like the plague. And i'd advise you to do the same.

PS: I am pleased to see you old fellers are finally warming
up to the wonderful OOP paradigm, but i gotta say, what is
most entertaining to me is watching you seasoned pros
struggle with the simplist OOP concepts. And don't get
angry, because i'm laughing at you, not with you. (or is it
the other way 'round??? o_O)



More information about the Python-list mailing list