Yaniv Haddad
Yaniv Haddad

Reputation: 59

how to move function to class? python

I would like to to use service functions in a classmethod, 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()

Yet I receive this error:

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

Any ideas how to make it work?

Upvotes: 3

Views: 917

Answers (1)

Kallz
Kallz

Reputation: 3523

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

Upvotes: 6

Related Questions