Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow __init__ to allow 1 or no parameters in python

Tags:

python

class

Right now I have this class:

class foo():
  def __init__(self):
      self.l = []

Right now, I can set a variable to foo without an argument in the parameter because it doesn't take one, but how can I allow this continue to take no required parameters, but also put in a list if I wanted into foo()? Example:

>>> f = foo([1,2,3]) #would be legal and
>>> f = foo() # would be legal
like image 961
user12074577 Avatar asked Apr 20 '13 03:04

user12074577


1 Answers

def __init__(self, items=None):
    if items is None: items = []
    self.l = items

In response to @Eastsun's edit, I propose a different structure to __init__

def __init__(self, items=()):
    ''' Accepts any iterable 
    The appropriate TypeError will be raised if items is not iterable '''
    self.l = list(items)

Note that lowercase l is a bad name, it can be confused with 1

like image 117
jamylak Avatar answered Sep 28 '22 01:09

jamylak