Search code examples
pythonpython-descriptors

Python - __get__ is not called for my class


Here is my code :

class Argument :
    def __init__( self, argType, argHelp = None ) :
        self.type = argType
        self.help = argHelp
    def __get__(self, obj, type=None):
        print("__get__")
        return self.type

a  = Argument( "my_ret_value" , argHelp = "some help text "  )

What I want is this to return my_ret_value but instead I get :

<__main__.Argument instance at 0x7ff608ab24d0>

I've read Python Descriptors examples and if I change my code to follow that it works - but why can't I do it on my class as it is? Is there any other way?

EDIT :

Thanks for the comments, I had not understand it very well. Could __repr__ solve my issue?

What I want is that I am changing a string value into an Object, I want to treat this object as a string, with some extra attributes.


Solution

  • You can use your decriptor class as follows:

    class B:
        a = Argument("my_ret_value", argHelp="some help text")
    
    b = B()
    b.a
    # __get__
    # 'my_ret_value'
    

    When set as class attribute on another class and accessed via an instance of said class, then the __get__ method of the descriptor is called. See the Descriptor How-To Guide.