Can You Set An Attribute To A Method In Python
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 anAttributeErrorbeing 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' yetSolution 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"