0
class Transformer:
    validate = None
    operator = None

    def func(self, X):
        if self.validate:
            self.validate(X)

        if self.operator:
            return self.operator(X)


def notstr(x):
    if not isinstance(x, str):
        raise TypeError("this variable is not a str")


class PreTF(Transformer):
    validate = notstr


class ListTF(PreTF):
    operator = list


if __name__ == "__main__":
    l = ListTF()
    res = l.func("123")
    print(res)

Then there would get errors. It's weird to get 2 arguments.

Traceback (most recent call last):
  File ".\src.py", line 31, in <module>
    res = l.func("123")
  File ".\src.py", line 7, in func
    self.validate(X)
TypeError: notstr() takes 1 positional argument but 2 were given

Let us check what the arguments are.

def notstr(x, *_):
    print("x:", x)
    print("*_:", _)
    if not isinstance(x, str):
        raise TypeError("this variable is not a str")

And still running that example, you would this.

The first one is an object argument. The second one is what we input "123".

x: <__main__.ListTF object at 0x000001FE49B493A0>
*_: ('123',)
Traceback (most recent call last):
  File ".\src.py", line 33, in <module>
    res = l.func("123")
  File ".\src.py", line 7, in func
    self.validate(X)
  File ".\src.py", line 20, in notstr
    raise TypeError("this variable is not a str")
TypeError: this variable is not a str

One method to fix this.

class PreTF(Transformer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.validate = notstr

But why the init code would get in trouble?

Zero
  • 11
  • 4

0 Answers0