oop - Assign external function to class variable in Python -


i trying assign function defined elsewhere class variable can later call in 1 of methods of instance, this:

from module import my_func  class bar(object):     func = my_func     def run(self):         self.func()  # runs function 

the problem fails because when doing self.func(), instance passed first parameter.

i've come hack seems ugly me, has alternative?

in [1]: class foo(object):    ...:     func = lambda *args: args    ...:     def __init__(self):    ...:         print(self.func())    ...:  in [2]: class foo2(object):    ...:     funcs = [lambda *args: args]    ...:     def __init__(self):    ...:         print(self.funcs[0]())    ...:  in [3]: f = foo() (<__main__.foo object @ 0x00000000044bfb70>,)  in [4]: f2 = foo2() () 

edit: behavior different builtin functions!

in [13]: math import pow  in [14]: def pow_(a, b):    ....:     return pow(a, b)    ....:  in [15]: class foo3(object):    ....:     func = pow_    ....:     def __init__(self):    ....:         print(self.func(2, 3))    ....:  in [16]: f3 = foo3() --------------------------------------------------------------------------- typeerror                                 traceback (most recent call last) <ipython-input-16-c27c8778655e> in <module>() ----> 1 f3 = foo3()  <ipython-input-15-efeb6adb211c> in __init__(self)       2     func = pow_       3     def __init__(self): ----> 4         print(self.func(2, 3))       5  typeerror: pow_() takes 2 arguments (3 given)  in [17]: class foo4(object):    ....:     func = pow    ....:     def __init__(self):    ....:         print(self.func(2, 3))    ....:  in [18]: f4 = foo4() 8.0 

python functions descriptor objects, , when attributes on class accessing them instance causes them bound methods.

if want prevent this, use staticmethod function wrap function in different descriptor doesn't bind instance:

class bar(object):     func = staticmethod(my_func)     def run(self):         self.func() 

alternatively, access unbound function via __func__ attribute on method:

def run(self):     self.func.__func__() 

or go directly class __dict__ attribute bypass descriptor protocol altogether:

def run(self):     bar.__dict__['func']() 

as math.pow, that's not python function, in written in c code. built-in functions written in c, , not descriptors.


Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -