Marcus Ottosson
Marcus Ottosson

Reputation: 3301

How to use descriptors with attributes of instances?

I read the docs and saw that descriptors had to be used with class attributes only. What would be an acceptable way of using them within instances of that class?

I.e.

class Attribute( object ):
    def __init__(self, value):
        self.value = value

    def __get__(self, obj, objtype):
        print "GETTING"
    def __set__(self,obj,val):
        print "SETTING"

class MyClass( object ):
    def __init__(self):
        self.myname = Attribute( '' )

name = MyClass()
print name.myname

Upvotes: 1

Views: 161

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798576

Manipulate them via obj, the second argument to the descriptor's methods.

Upvotes: 2

Related Questions