-4

How do we pass a list as an argument of a python class?

class My_Class:
    def __init__(self, att, mylist[]):
        self.att=att
        self.mylist = mylist[]
Azazel
  • 167
  • 3
  • 12
  • what have you tried? did it work? – depperm Nov 26 '18 at 13:34
  • https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters – Attila Bognár Nov 26 '18 at 13:35
  • 5
    Just get rid of all the `[]`…!? – deceze Nov 26 '18 at 13:35
  • 4
    You just pass it - there's no special syntax... – Jon Clements Nov 26 '18 at 13:35
  • 2
    You can leave off the square brackets `[]` in both your parameter list and the assignment statement. As long as the *type* of `mylist` is a list, it will be treated as a list. – DatHydroGuy Nov 26 '18 at 13:36
  • 2
    @DatHydroGuy `s/can/must/` – chepner Nov 26 '18 at 13:46
  • 2
    On the off-chance that you are asking about type hinting, it would be `def __init__(self, att, mylist: List[Any])` (assuming you have imported the names `List` and `Any` from the `typing` module). – chepner Nov 26 '18 at 13:49
  • 1
    Side note: Please don't name your classes like `My_Class`. That looks like [Wordpress class naming conventions](https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#naming-conventions) which are, IMO, some of the objectively worst conventions on the planet. But we can avoid the "IMO" part here since Python has an [official style guide](https://www.python.org/dev/peps/pep-0008/)! Following PEP 8, you might name your class `MyClass`. – ChrisGPT was on strike Nov 26 '18 at 13:50

3 Answers3

2

There's nothing to it, really. In Python we do not need to declare the type of parameters:

class My_Class:
    def __init__(self, att, mylist):
        self.att = att
        self.mylist = mylist
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • The how do I print the list? print(instance.mylist)? – Azazel Nov 26 '18 at 13:41
  • 5
    @Azazel, why would you think you should use `instance`? It looks like you would benefit from a Python tutorial. Start with the basics, which will cover things like variable names and types (so you won't make mistakes like `mylist[]`), then look for one that deals with object-oriented Python code. – ChrisGPT was on strike Nov 26 '18 at 13:42
  • by instance I meant instance of that My_Class.....something like: class1=My_Class('ABC', ['123','456','789']) – Azazel Nov 26 '18 at 13:47
2

You don't need to specify that it is a list. Python is a dynamically and strongly typed language.

class My_Class:
    def __init__(self, att, mylist):
        self.att = att
        self.mylist = mylist
chepner
  • 497,756
  • 71
  • 530
  • 681
edilio
  • 1,778
  • 14
  • 13
0

You simply pass a reference to the list

class My_Class:
def __init__( self, att, mylist ):
    self.att=att
    self.mylist = mylist
rachid el kedmiri
  • 2,376
  • 2
  • 18
  • 40