Can you set an attribute to a method in python

python, python-3.x

Solution

`type( test.getString )` is `builtins.method` and from the documentations ( methods ),

since method attributes are actually stored on the underlying function object (`meth.__func__`), setting method attributes on bound methods is disallowed. Attempting to set an attribute on a method results in an `AttributeError` being raised.

There are (at least) two possible solutions depending on which behaviour you are looking for. One is to set the attribute on the class method:

class Test:
    def getString(self, var):
        setattr(Test.getString, "string", var)
        return self.getString

test = Test()
test.getString("myString").string  # > "myString"

test2 = Test()
test2.getString.string # > this is also "myString"

and the other is to use function objects:

class Test:
    class getStringClass:
        def __call__ ( self, var ):
            setattr( self, "string", var )
            return self

    def __init__( self ):
        self.getString = Test.getStringClass( )

test = Test( )
test.getString( "myString" ).string   # > "myString"

test2 = Test()
test2.getString.string  # > this is error, because it does not
                        # have the attribute 'string' yet

Problem

I'm wondering if it is possible to use setattr to set an attribute to a method within a class like so because when I try I get an error which is going to be shown after the code: ``` class Test: def getString(self, var): setattr(self.getString, "string", var) return self.getString test = Test() test.getString("myString").string ``` Which errors `AttributeError: 'method' object has no attribute 'string'` so I tried it without putting `.string` and just tried `test.getString("myString")` Same error, but then I tried it without the using the class just like this ``` def getString(var): setattr(getString, "string", var) return getString getString("myString").string ``` It returned "myString" like I wanted it to, so how would I do this within a class and why does it work outside of one but inside of one?

Original source

Related problems