Customizing class attribute access in classic classes

Geoff Bache geoff.bache at gmail.com
Sun Oct 30 06:02:35 EDT 2011


Thanks for this Steven. I'm however gettings some pretty odd effects,
both on method access and inheritance. I expanded your example a
bit...

class Meta:
    def __init__(self, name, bases, namespace):
        self.__name__ = name
        self.__bases__ = bases
        self.__dict__ = namespace
    def __str__(self):
        return "<Meta instance>"
    __repr__ = __str__
    def __getattr__(self, name):
        return "Customized " + name
    def __call__(self):
        return self

class Base:
    def basemethod(self):
        return "base"


class A(Base):
    __metaclass__ = Meta
    def method(self):
        return "answer"

The effect seems to be to make all methods of A into static methods,
and to ignore its base classes altogether:

>>> a = A()
>>> print a.blah2
Customized blah2
>>> print a.method()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: method() takes exactly 1 argument (0 given)
>>> print a.method(1)
answer
>>> print A.method(1)
answer
>>> print a.basemethod()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>> isinstance(a, Base)
False

Regards,
Geoff Bache



More information about the Python-list mailing list