How do I move a function into a class? python

I would like to use utility functions in a class method where the service function is defined somewhere else. I want to be dynamic, so I can define different functions in different situations. I've tried this:

def print_a():
    print 'a'

class A:
    func = print_a
    @classmethod
    def apply(cls):
        cls.func()

A.apply()

      

But I am getting this error:

unbound method print_a() must be called with A instance as first argument (got nothing instead)

Any ideas how to get it to work?

+3


source to share


1 answer


you can use call

def print_a():
    print 'a'

class A:

    func = print_a.__call__

    @classmethod
    def apply(cls):
        cls.func()

A.apply()

      



Output

a

      

+6


source







All Articles