Answer the question
In order to leave comments, you need to log in
How to unambiguously redefine addition?
There is a function with one main argument and several additional ones. The additional arguments are optional, have their own class, and are only needed to fine-tune the function. Let all additional arguments be listed in this list [A, B, C, D]. And func(x) is a function.
How to make it so that instead of writing func(x, A, B, D) you can use func(x, A+B+D) . A simple idea comes to mind to redefine addition for the extra argument class. For example, write the names of the arguments with a separator and pass them as a string A+B+D = "A$B" + D = "A$B$D", and then the function will be parsed. This method does not look very elegant. I would like to know how to do it right in such cases.
Answer the question
In order to leave comments, you need to log in
I don't see why not just make those extra arguments of yours key and optional. Well, something like this:
from typing import Any, Optional
class A:
def __init__(self, option: str):
self._option = option
def option(self) -> str:
return self._option
class B:
def __init__(self, option: int):
self._option = option
def option(self) -> int:
return self._option
def func(x: Any, *, a: Optional[A] = None, b: Optional[B] = None) -> None:
if a is not None:
print(a.option())
if b is not None:
print(b.option())
if __name__ == '__main__':
func(None, a=A('aaa'))
func(None, b=B(666))
func(None, a=A('AAA'), b=B(666))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question