0
I need to define a class in Python, which will receive a series of parameters. I would like to make the methods receive arguments of a certain type. An example of the code:
class Teste():
def __init__(self, arg1: tuple = (8,6)):
self.arg1=arg1
def setArg(self,arg1):
self.arg1=arg1
So, as soon as I called the class builder, or the method .setArg()
, they only accept, for example, tuples of size 2 as argument (or other cases like integer or string).
In this code, if I put an entire argument, for example, t = Teste(arg1 = 10)
or t.setArg(10)
, it would return an error saying that the argument must be a tuple.
There is some way to do this without having to create a code within each method to check the type and, if the type restriction is not respected, raise an error message?
See the answer accepted in the question considered duplicated. If you have more specific questions later, you can create another question - but I’ll give you a comment that I didn’t write in the answer to the linked question above:
– jsbueno
Python, being a dynamic language, nay has the concept of implicit check of arguments. Everything that is received in a function is a "Python object". What exists today is an optional mechanism for static check of arguments, which can be executed before the execution of the program - (that is, at a time equivalent to the "build" of the language project that needs an explicit compilation step). If you want to do this, follow the instructions in some "Mypy" usage tutorial (the "official" type checker" )
– jsbueno
I saw the answer to the other question, but forgot to remove my kkkkk. Thank you very much!
– Leonardo Araújo
You can leave that question there - because when someone goes to pick it up, you can do a different search that falls here first. For me, the important thing is to be clear: Python doesn’t do it automatically, and that’s a 'zero moment' language design option - just like with Javascript.
– jsbueno
What is not clear until one understands a lot is that attempts to activate restrictions of this type will imply checks at runtime, which has a cost in performance - while not making a check - for example, the person mana a string where it was a tuple by mistake - will give an error the same way - only when the program is running. To discover possible points where incorrect parameters are passed before program run, only with mypy static check.
– jsbueno