zjm1126
zjm1126

Reputation: 66637

how can i use '__set__'

class A(object):
    def __get__(self, instance, owner):#why i can't find argument 'key',where is 'key'
        #print ower.instance
        print instance,owner
    def __set__(self,instance,value):
        instance=value

class X(object):
    a = A()

xx=X()
xx.a='aaa'
print xx.a#None

Upvotes: 1

Views: 340

Answers (3)

Alex Martelli
Alex Martelli

Reputation: 881555

Hettinger's HowTo Guide for Descriptors covers this well. Quoting from it:

Descriptor Protocol

descr.__get__(self, obj, type=None) --> value

descr.__set__(self, obj, value) --> None

descr.__delete__(self, obj) --> None

That is all there is to it.

So, you can name the arguments however you wish, but there's typically no argument named key to __get__ (no idea why you're trying to find it).

Again an example from that URL:

class RevealAccess(object): """A data descriptor that sets and returns values normally and prints a message logging their access. """

def __init__(self, initval=None, name='var'):
    self.val = initval
    self.name = name

def __get__(self, obj, objtype):
    print 'Retrieving', self.name
    return self.val

def __set__(self, obj, val):
    print 'Updating' , self.name
    self.val = val

So normally you set self.something in __init__ (and/or __set__ if you define it), and return something based on self.something in __get__. Of course this example just prints the "something" on getting and setting, normally you'd do something more substantial;-).

Upvotes: 4

Leonardo Santagada
Leonardo Santagada

Reputation: 146

I think you could read about descriptors:

http://users.rcn.com/python/download/Descriptor.htm

Or maybe what you want is to customize attribute access:

http://docs.python.org/reference/datamodel.html#customizing-attribute-access

Maybe this pointers can help you, or maybe you can be more specific?

Upvotes: 1

Adam Crossland
Adam Crossland

Reputation: 14213

Do you mean to be using __getattribute__? It has a parameter that is commonly called key; although it can be any name at all. And the definition that you have for __set__ looks like it should be for __setattribute__

Upvotes: 2

Related Questions