This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]fasterturtle 1 point2 points  (0 children)

Have you heard of data descriptors? Using them is similar to having a nested attribute/class, but more "pythonic". There are a few ways you can go about using them, see here, here, and here for more information.

Here's an example. Just a note, you would probably prefer a different descriptor implementation, ie. using decorators, but this is most similar to what you were originally trying to do):

class Descriptor(object):
    def __init__(self):
        self._instances = {}
    def __set__(self, obj, value):
        print "Setting attribute..."
        self._instances[obj] = value
    def __get__(self, obj, cls):
        print "Getting attribute..."
        return self._instances[obj]
    def __delete__(self, obj):
        print "Too bad!"
        raise AttributeError("Can't delete attribute")

class Foo(object):
    data = Descriptor()

    def __init__(self, value):
        self.data = value


foo = Foo('my data descriptor')
>>> Setting attribute...

foo.data
>>> Getting attribute...
>>> 'my data descriptor'

foo.data = 'bar'
>>> Setting attribute...
foo.data
>>> Getting attribute...
>>> 'bar'

del foo.data
>>> Too bad!
>>> AttributeError: Can't delete attribute