Python: decorated static method returns non-invoked method

I had a small problem with the design of a static method in Python. I think the following code best reflects my problem:

def decorator(func):
    print callable(func)
    return func

class Foo():
    @decorator
    @staticmethod
    def bar():
        return

# outputs False

print callable(Foo.bar) 
# outputs True

This seems to be a mistake. I assume this occurs because when a method Foo.baris passed to the decorator, it is a function, not a method. This is the only reason I see that it cannot be called, because if we decorate a standard function, it cannot be called, as shown below.

@staticmethod
def function():
    return

print callable(function) 
# outputs False

, staticmethod / - ? , __call__, , callable, .

+5
3

- . staticmethod . descriptors, , Cls.static_method, , (.. ) static_method Cls. , , . , staticmethod , .. , .

+4

, , :

- . , . , , . , , , . staticmethod().

+4

staticmethod, , , , .

class staticmethod(object):
    """Make @staticmethods play nice with @memoize."""

    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        """Call the static method with no instance."""
        return self.func(*args, **kwargs)

This does not use the descriptor protocol and as such behaves quite differently than the built-in staticmethodinside, however in practice it makes functions called as class attributes, instance attributes and even function attributes (i.e. ve wrapped your class in a decoration function, this implementing staticmethod will still allow you to call your static methods as attributes in the wrapper function).

0
source

All Articles