the annoying, verbose self

Iain King iainking at gmail.com
Tue Nov 27 12:44:46 CET 2007


On Nov 27, 9:20 am, Roy Smith <r... at panix.com> wrote:
> In article <474bdf4f$0$19226$426a7... at news.free.fr>,
>  Bruno Desthuilliers <bruno.42.desthuilli... at wtf.websiteburo.oops.com>
>
>
>
>  wrote:
> > Steven D'Aprano a écrit :
> > > On Mon, 26 Nov 2007 21:48:36 +0100, Ton van Vliet wrote:
>
> > >> On Mon, 26 Nov 2007 20:14:50 +0100, Bruno Desthuilliers
> > >> <bdesth.quelquech... at free.quelquepart.fr> wrote:
>
> > >>>> However, I was more thinking in terms of attributes only
> > >>> Too bad : in Python, everything's an object, so 'methods' are attributes
> > >>> too.
> > >> Right, but I'm sure *you* know a way to distinguish between them
>
> > Yes : reading the doc. But that's something the compiler will have hard
> > time doing.
>
> > >> (I'm
> > >> just a beginner ;-)
>
> > > All methods are attributes. Not all attributes are methods. The usual way
> > > to see if something is a method is to try calling it and see what
> > > happens, but if you want a less informal test, try type():
>
> > >>>> type(''.join)
> > > <type 'builtin_function_or_method'>
> > >>>> type(Foo().foo)  # with the obvious definition of Foo
> > > <type 'instancemethod'>
>
> > Fine. Now since Python let you define your own callable types and your
> > own descriptors, you can as well have an attribute that behave just like
> > a method without being an instance of any of the method types - so the
> > above test defeats duck typing. And since you can have callable
> > attributes that are definitively not methods, you can't rely on the fact
> > that an attribute is callable neither.
>
> If you want to have a little fun:
>
> class peverse:
>     def __call__(self):
>         raise AttributeError ("peverse instance has no __call__ method")
>
> x = peverse()
> x()


Horrific cluge:
--

def noself(func):
    def t(*args, **kwargs):
        self = args[0]
        g = globals()
        delete = []
        for varname in dir(self):
            if not varname.startswith("__") and varname not in g:
                g[varname] = self.__getattribute__(varname)
                delete.append(varname)
        func(*args, **kwargs)
        for varname in delete:
            del(g[varname])
    return t


class Test(object):
    x = 1

    @noself
    def test(self):
        print x


>>> foo = Test()
>>> foo.test()
1

--

FTR, I won't be using this :)  I do like this syntax though:

class Vector:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
    def abs(self):
        using self:
            return math.sqrt(.x*.x + .y*.y + .z*.z)

Iain



More information about the Python-list mailing list