extending method descriptors

Peter Otten __peter__ at web.de
Thu Jun 25 12:53:12 EDT 2009


Michael Sliczniak wrote:

> Suppose I have this:
> 
> Python 2.5.1 (r251:54863, Feb  6 2009, 19:02:12)
> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>>>> class A(object):
> ...     __slots__ = ('x', 'y')
> ...
>>>> a = A()
>>>> b = A()
> 
> So I am using descriptors (and I want to). I also would like to have
> methods A.x.foo(), A.x.bar(), A.y.foo(), and A.y.bar() and my idea was
> to extend member_descriptor, but it seems that I cannot:
> 
>>>> type(A.x)
> <type 'member_descriptor'>
>>>> class my_descriptor(type(A.x)):
> ...     def foo():
> ...             return 1
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: Error when calling the metaclass bases
>     type 'member_descriptor' is not an acceptable base type
> 
> Is there some way, outside of using C, to be able to do what I want.
> Yes I want a.x and b.x to be different, but type(a).x.foo(), type
> (b).x.foo(), and A.x.foo() should all be the same. I have tried other
> approaches and get exceptions of one flavor or another with everything
> I have tried.

If you define an attribute with the same name in both the class and its 
instances the instance attribute just hides the class attribute:

>>> class X(object):
...     def foo(self): return "yadda"
...
>>> class A(object):
...     def __init__(self, x):
...             self.x = x
...     x = X()
...
>>> a = A("foo")
>>> b = A("bar")
>>> a.x, b.x, type(a).x.foo(), type(b).x.foo()
('foo', 'bar', 'yadda', 'yadda')

This is probably not what you expected. So what are you really trying to 
achieve?

Peter




More information about the Python-list mailing list