class - How to allow __init__ to allow 1 or no parameters in python -
right have class:
class foo(): def __init__(self): self.l = [] right now, can set variable foo without argument in parameter because doesn't take one, how can allow continue take no required parameters, put in list if wanted foo()? example:
>>> f = foo([1,2,3]) #would legal , >>> f = foo() # legal
def __init__(self, items=none): if items none: items = [] self.l = items in response @eastsun's edit, propose different structure __init__
def __init__(self, items=()): ''' accepts iterable appropriate typeerror raised if items not iterable ''' self.l = list(items) note lowercase l bad name, can confused 1
Comments
Post a Comment