W
W
WorthToLive2020-05-21 03:08:11
Python
WorthToLive, 2020-05-21 03:08:11

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

2 answer(s)
S
Sergey Pankov, 2020-05-21
@WorthToLive

  1. It is necessary that classes A, B, C, D be descendants of one abstract class Base. An abstract class must declare an interface common to them.
  2. We need to make one more class G - a descendant of Base. G must contain inside a list of elements of class Base. In addition, G must implement all the abstract methods of its interface by calling the appropriate methods nested in its list of objects.
  3. The Base class must override the __add__ addition method. The result of the addition is an instance of G containing a list of the elements to be added.

A
Andy_U, 2020-05-21
@Andy_U

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 question

Ask a Question

731 491 924 answers to any question