Call a Python object variable as a function without passing the caller

I have a structure like this:

def foobar(): print('FOOBAR!') class SampleClass: foo = foobar def printfunc(self): self.foo() 

This does not work because the original foobar function cannot pass the self passed to it - it was not part of any class or object. Python won't let me add the @staticmethod decorator.

I cannot control the definition of foobar , and I may have to override the value of foo in subclasses.

How can I call foo without passing the object calling it?

+6
source share
2 answers

Decorators are simple functions , you should be able to explicitly call staticmethod(foobar) in the class definition

 class SampleClass: foo = staticmethod(foobar) def printfunc(self): self.foo() # Prints 'FOOBAR!' 
+6
source

User2357112 user comment seems to work as well:

 def foobar(): print('FOOBAR!') def foobaz(): print('FooBAZ!') class SampleClass: def foo(self): foobar() def printfunc(self): self.foo() class DerivedClass(SampleClass): def foo(self): foobaz() sample = SampleClass() sample.printfunc() # FOOBAR! derived = DerivedClass() derived.printfunc() # FooBAZ! 

If the return values ​​must pass, you will need return statements at all levels:

 def foobar(): print('FOOBAR!') return 'foo' def foobaz(): print('FooBAZ!') return 'baz' class SampleClass: def foo(self): return foobar() def printfunc(self): return self.foo() class DerivedClass(SampleClass): def foo(self): return foobaz() sample = SampleClass() s = sample.printfunc() # FOOBAR! print(s) # foo derived = DerivedClass() d = derived.printfunc() # FooBAZ! print(d) # baz 
+2
source

Source: https://habr.com/ru/post/984995/


All Articles