+ 1

Is this the correct way to code?

class b: def __init__(self, a, b): self.a = a[] self.b = b[]

18th Apr 2022, 5:33 PM
Lenoname
12 Respuestas
+ 7
You say you want your arguments to be lists. Python is dynamically typed, so there are no compile-time guarantees about the type of an argument. But you can do a few things to enforce certain types in functions (including the class constructor). Type hints are for information only, they are clues for the user of your class, what type of argument is expected. There are code analysis utilities (and IDE) that can verify if you used the correct type. def __init__(self, a: list, b: list): A more aggressive way is to stop the program when the argument is wrong, by explicitly checking the type. You can use type() or isinstance() functions for this, and your program can raise an error if the type of the passed variable is wrong. The program would break anyway, if you expect a list and something else is passed. if type(a) is not list or type(b) is not list: raise AttributeError("Must be list!") Example: https://code.sololearn.com/cBN7XNt4xjGE/?ref=app
19th Apr 2022, 2:46 AM
Tibor Santa
Tibor Santa - avatar
+ 2
Pass lists Or use self.a = [] self.b = [] # no parameters (a,b) need then
18th Apr 2022, 6:11 PM
Jayakrishna 🇮🇳
+ 1
Lenoname To avoid name confusion, I wrote class name as B .. Edited. Check again.. May you want to force to pass or use only list, then see @Tibor Santa way..but a little bit more advanced solution. But a strict way to program not to lead bugs...
19th Apr 2022, 8:42 AM
Jayakrishna 🇮🇳
+ 1
B = (baba)
20th Apr 2022, 9:06 AM
Debabrat Panda
Debabrat Panda - avatar
+ 1
M = (mama)
20th Apr 2022, 9:07 AM
Debabrat Panda
Debabrat Panda - avatar
0
class b: def __init__(self, a, b): self.a = a self.b = b
18th Apr 2022, 5:43 PM
Jayakrishna 🇮🇳
0
Jayakrishna🇮🇳 i want them to be lists
18th Apr 2022, 5:48 PM
Lenoname
0
What do u mean by pass lists?
18th Apr 2022, 6:32 PM
Lenoname
0
class B: def __init__(self, a, b): self.a = a self.b = b a = [] b = [] B(a, b) #passing a, b lists which is assigned for object edit: class name B
18th Apr 2022, 6:42 PM
Jayakrishna 🇮🇳
0
B(a, b)? U mean B = b(a, b)?
18th Apr 2022, 9:27 PM
Lenoname
0
self.a = [a]
18th Apr 2022, 11:47 PM
Mohamed Ayaou
0
I know
20th Apr 2022, 2:15 PM
GAME'S FIST