Skip to content Skip to sidebar Skip to footer

Can You Set An Attribute To A Method In Python

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: c

Solution 1:

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:

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

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

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

and the other is to use function objects:

classTest:classgetStringClass:def__call__( self, var ):
            setattr( self, "string", var )
            returnselfdef__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

Solution 2:

So, I found a way but it's not really how I wanted to do it personally. If anyone does find another way to do the following code feel free to comment on how to do it.

class Test:
    def getString(self, string):
        setattr(self,"newString",self)
        self.newString.string = stringreturnself.newString

Like I said, I don't feel like I accomplished anything by doing it that way, but it works for what I need and if you do find another way comment below.

Post a Comment for "Can You Set An Attribute To A Method In Python"