+ 1
Is this the correct way to code?
class b: def __init__(self, a, b): self.a = a[] self.b = b[]
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
+ 2
Pass lists
Or use
self.a = []
self.b = [] # no parameters (a,b) need then
+ 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...
+ 1
B = (baba)
+ 1
M = (mama)
0
class b:
def __init__(self, a, b):
self.a = a
self.b = b
0
Jayakrishna🇮🇳 i want them to be lists
0
What do u mean by pass lists?
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
0
B(a, b)?
U mean
B = b(a, b)?
0
self.a = [a]
0
I know