1

I'm using "new style" classes in Python 2.6 and am having trouble with __getattr__ in a subclass.

If the subclass implements like such...

def __getattr__(self, name):
    if self.__folderDict.has_key(name):
        if name == 'created':
            return doSomethingSpecial(self.__folderDict[name])
        return self.__folderDict[name]
    else:
        raise AttributeError()

It's not clear to me why my attribute exception gets thrown for a reference to __name__ ?

My understand is that __getattr__ should not even get called and that __name__ should be fullfilled by __getattribute__ since I'm using new style?

Here's a more complete example...

class Base(object):
    @staticmethod
    def printMsg(msg, var):
        print msg + str(var)
        return

    def printName(self):
        Base.printMsg('#', self.__name__)
        return

class Derived(Base):
    def __getattr__(self, name):
        if self.__testDict.has_key(name):
            return self.__testDict[name]
        else:
            raise AttributeError()

    __testDict = {'userid': 4098}


d = Derived()
print d.userid
d.printName()

The result is...

4098
Traceback (most recent call last):
File "D:/.../Scratch/scratch01.py", line 24, in <module>
d.printName()
File "D:/.../Scratch/scratch01.py", line 17, in __getattr__
raise AttributeError()
AttributeError
  • 2
    Can you show the actual calling code and the traceback? – bgporter Mar 17 '12 at 15:49
  • Agree with the former comment, your information is not very detailed and clear, people may feel confused when they want to write answers. But according to your understanding of __getattr__ and __getattribute__, [this post](http://stackoverflow.com/questions/3278077/difference-between-getattr-vs-getattribute-in-python) seems useful to you. – Reorx Mar 17 '12 at 16:06

1 Answers1

1

__name__ is predefined for class objects, not instances, and you don't define __name__ anywhere before trying to read it. So _getattr__ is called (since __name__ can't be found via normal lookup) and results in an exception. I suspect that what you actually want is:

...
def printName(self):
    Base.printMsg('#', self.__class__.__name__)
    return
...
aquavitae
  • 17,414
  • 11
  • 63
  • 106