1

Suppose that I have class A and this class has a method called function. Can I assign a cache as a property to this method? In the sense that I could call it like a property?

class A:
    def __init__(self,value):
        self.value=value
    def function(self,a):
        """function returns a+1 and caches the value for future calls."""
        cache=[]
        cache.append([a,a+1])
        return a+1;
a=A(12)
print a.function(12)
print a.function.cache

Which gives me the error:

AttributeError: 'function' object has no attribute 'cache'

I know it is possible to assign a cache to the main class but I am looking for a possible way of assigning it as a property to the method object.

4

1 回答 1

1
class A:
    def __init__(self,value):
        self.value=value
        self.cache = {}
    def function(self,a):
        """function returns a+1 and caches the value for future calls."""

        # Add a default value of empty string to avoid key errors,
        # check if we already have the value cached
        if self.cache.get(a,''):
            return self.cache[a]
        else:
            result = a + 1
            self.cache[a] = result
            return result

As far as I know there is no way of having the cache as a property of the method. Python doesn't have such a feature. But I think perhaps this solution will satisfy your needs.

EDIT

Upon further research, there is indeed a way to do this in Python 3

class A:
    def __init__(self,value):
        self.value=value

    def function(self,a):
        """function returns a+1 and caches the value for future calls."""
        # Add a default value of empty string to avoid key errors,
        # check if we already have the value cached
        if self.function.cache.get(a,''):
            return self.function.cache[a]
        else:
            result = a + 1
            self.function.cache[a] = result
            return result
    function.cache = {}


a=A(12)
print(a.function(12))
print(a.function.cache)

This is because in Python 3 instance methods are just functions. BTW in Python 2 it is indeed possible to add attributes to functions, but not to instance methods. If you need to use Python 2 then there is a solution to your problem involving decorators that you should look into.

于 2013-06-27T14:40:36.593 回答