Functions are similar to most other objects in which you can freely add attributes to them. Methods, on the other hand ... conceptually they are just functions, but they behave somewhat differently (impicity pass self ) and, therefore, are implemented with a little glue added around the functions.
Each time self.getString is evaluated, a new method object (bound) is created, which is a thin wrapper around the base function (which you can access as Test.getString ). These method objects do not allow you to add attributes, and even if they did, your code would not work because it juggles several different method objects (although they all wrap the same function).
You cannot do this work with related methods. Since you presumably want the string to be bound to the Test object (indirectly by binding to its method), you can make it a Test attribute. You can even create your own object that behaves like a method, but allows attributes (you need to explicitly add it to __init__ ), but honestly, this is probably the best way to separate data and methods. If, on the other hand, you want to attach this attribute to a base function (which would mean that it would be used by all instances of Test ), you can simply set the attribute to Test.getString .
source share