[Python] Python descriptors __get__ and __set__

Discussão em 'Python' iniciado por Stack, Janeiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I am sure this will be marked as a duplicate, but I truly don't understand what I'm looking at. I've checked The python documentation on Descriptors, but I have been "programming" in Python for two weeks now and I don't really know what I'm looking for!

    This is what I got:

    >>> class Blub(object):
    ... def __init__(self, value):
    ... print('Blub is ' + value)
    ... self.value = value
    ... def __get__(self):
    ... print('Blub gets ' + self.value)
    ... return self.value
    ... def __set__(self, value):
    ... print('Blub becomes ' + value)
    ... self.value = value
    ...
    >>> class Quish(object):
    ... def __init__(self, value):
    ... self.blub = Blub(value)
    ... def __get__(self):
    ... return self.blub
    ... def __set__(self, value):
    ... self.blub = Blub(value)
    ...


    The following is what I want to happen and don't know how to do:

    >>> a = Quish('One')
    Blub is One
    >>> a.blub
    Blub gets One
    'One'
    a.blub = 'Two'
    Blub becomes Two


    What do I do in Blub or Quish in order for this to happen. I have really simple classes here, but I have a much more intricate version which works perfectly but only if I type:

    >>> a.blub.__get__()


    I thought that the point of these descriptors was to make it unnecessary to actually write get() and set(). How do I make it behave like I would like, or can Python not do that?

    Continue reading...

Compartilhe esta Página