How to save a function in a class attribute?

In my code, I have a class where one method is responsible for filtering some data. To enable customization for descendants, I would like to define the filtering function as an attribute of the class, as shown below:

def my_filter_func(x):
    return x % 2 == 0

class FilterClass(object):

    filter_func = my_filter_func

    def filter_data(self, data):
        return filter(self.filter_func, data)

class FilterClassDescendant(FilterClass):

    filter_func = my_filter_func2

However, such code raises a TypeError, since filter_func receives an "I" as the first argument. What is the pythonic way of handling such use cases? Perhaps I should define my filter filter_func as a regular class method?

+4
source share
2 answers

Could you just add it as a plain old attribute?

def my_filter_func(x):
    return x % 2 == 0

class FilterClass(object):

    def __init__(self):
        self.filter_func = my_filter_func

    def filter_data(self, data):
        return filter(self.filter_func, data)

Alternatively, make it be a static method:

def my_filter_func(x):
    return x % 2 == 0

class FilterClass(object):

    filter_func = staticmethod(my_filter_func)

    def filter_data(self, data):
        return filter(self.filter_func, data)
+4
source

Python . - UnboundMethod ( , ).

( , ), Python UnboundMethod (.. , ).

UnboundMethod :

def myfunction(a, b):
    return a + b

class A(object):
    a = myfunction

A.a(1, 2)
#prints 3

. , :

A().a(1, 2)

, , (, getattr) , UnboundMethod, im_self (im_self im_func UnboundMethod). , , im_func. , im_func, , im_self. , (, ).

, Python :

  • as-is, @staticmethod. , UnboundMethod. , .
  • , ( , ), (INSTEAD of self: cls), , - @classmethod.

:

class A(object):
    a = staticmethod(lambda a, b: a + b)

A.a(1, 2)
A().a(1, 2)

.

:

def add_print(cls, a, b):
    print cls.__name__
    return a + b

class A(object):
    ap = classmethod(add_print)

class B(A):
    pass

A.ap(1, 2)
B.ap(1, 2)
A().ap(1, 2)
B().ap(1, 2)

.

+2

All Articles