I have a structure something like this:
def foobar():
print('FOOBAR!')
class SampleClass:
foo = foobar
def printfunc(self):
self.foo()
This doesn't work because the original foobar function can't handle self
being passed to it -- it wasn't part of any class or object to begin with. Python won't let me add the @staticmethod
decorator either.
I have no control over 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?
Using the global statement If you want to assign a value to a name defined outside the function, then you have to tell Python that the name is not local, but it is global. We do this using the global statement. It is impossible to assign a value to a variable defined outside a function without the global statement.
Python passes arguments neither by reference nor by value, but by assignment.
To use functions in Python, you write the function name (or the variable that points to the function object) followed by parentheses (to call the function). If that function accepts arguments (as most functions do), then you'll pass the arguments inside the parentheses as you call the function.
Decorators are plain functions, you should be able to call staticmethod(foobar)
explicitly in the class definition
class SampleClass:
foo = staticmethod(foobar)
def printfunc(self):
self.foo() # Prints 'FOOBAR!'
The approach from user2357112's comment seems to work, too:
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 return values shall make it through, you need return
statements on all levels, though:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With