Reputation: 1991
For example I have
class A:
def f(self, x, y, z):
# do something with x, y, z
Is it possible to override f without retyping "self, x, y, z". Basically I have a class with function with 10 arguments, and intend on having many classes extending it, so I would prefer not to type the arguments every time. Please do not just tell me to pass a list/dictionary of all the arguments.
Upvotes: 2
Views: 3331
Reputation: 10193
class A:
def facade_f(self, x, y, z):
self._real_f({'x': x, 'y': y, 'z': z})
def _real_f(self, params):
# do something with params['x'], params['y'], params['z']
class B(A):
def _real_f(self, params):
# do something with params['x'], params['y'], params['z']
It's not a true overriding, but you expose a nice interface with all named parameters, can check their types and values in the facade_f
method, and still type very little when extending it.
Working example:
class A:
def facade_f(self, x, y, z):
self._real_f({'x': x, 'y': y, 'z': z})
class B(A):
def _real_f(self, params):
print params['x'], params['y'], params['z']
B().facade_f(1, 2, 3)
Upvotes: 2
Reputation: 251618
No. If you want the overridden function to have the same arguments, you need to type the same arguments. You could override it to have different arguments, so there's no way to magically know that you want it to have the same arguments.
The only way to avoid this is to use *args
and/or **kwargs
, but you seem to be saying you don't want to do that. (Also, this is not quite the same as actually defining the function with the right arguments, in terms of where/when errors are raised if you call with the wrong arguments.)
Upvotes: 4