newbie's version of properties.

Karthik Gurumurthy karthikg at aztec.soft.net
Mon Jan 14 22:55:45 EST 2002


hi all,

I just blindly followed this instruction from "What's new in python2.2"
article.

>>>>
For example, when you write obj.x, the steps that Python actually performs
are:
descriptor = obj.__class__.x
descriptor.__get__(obj)
>>>>
So i assumed that

when you write obj.x = val, the steps that Python "must" actually be
performing should be:

descriptor = obj.__class__.x
descriptor.__set__(obj,value)

and luckily, most of the guesses turn out to be true in python :-).

and then wrote my version of the "properties" in python

There should be a better way of writing it. Any suggestions.

moreover in addition to the "obj" , __get__ is getting a third argument
which happens to be the type of the instance we are operating on.
Any idea as to why the type of the object is getting passed along with other
things?

Now does this mean all these descriptors are present as static members of
the class since mine is.?
i mean x in Test looks like a static member.

class myproperty(object):

    def __init__(self,getM=None,setM=None):
        self._get = getM
        self._set = setM
    def __get__(self,obj,*args):
        return self._get(obj)
    def __set__(self,obj,value):
        self._set(obj,value)

class Test(object):

    def __init__(self,val):
        self._x = val

    def getx(self):
        return self._x

    def setx(self,val):
        self._x = val

    x = myproperty(getx,setx)

if __name__ == '__main__':
    t = Test(10)
    print t.x
    t.x = 100
    print t.x




More information about the Python-list mailing list