Home > Blockchain >  How to define default list in python class
How to define default list in python class

Time:09-16

class points():

  def __init__(self,a1,b1,c1,d1):
    self.a1=a1
    self.b1=b1
    self.c1=c1
    self.d1=d1


  def plot(self):
    xs=[self.a1[0],self.b1[0],self.c1[0],self.d1[0]]                           
    ys=[self.a1[1],self.b1[1],self.c1[1],self.d1[1]] 
    print(xs)
    print(ys)                           
    colors=['c','m','b','y']

a1=points([1,2],[2],[3,4],[4,5])
a1.plot()

How to define a default list so that when I am not providing value to b1[1] , it doesn't give error?

CodePudding user response:

this could be an option but I am not sure about the question.

class points():

  def __init__(self,a1,b1,c1,d1):
    self.a1=a1
    self.b1=b1
    self.c1=c1
    self.d1=d1


  def plot(self, default_val=0):
    elements = [self.a1,self.b1,self.c1,self.d1]
    xs=[val[0] if type(val) is list and len(val)>0 else default_val for val in elements]                           
    ys=[val[1] if type(val) is list and len(val)>1 else default_val for val in elements] 
    print(xs)
    print(ys)                           
    colors=['c','m','b','y']

a1=points([1,2],[2],[3,4],[4,5])
a1.plot()
>>>
[1, 2, 3, 4]
[2, 0, 4, 5]

a1.plot(14)
>>>
[1, 2, 3, 4]
[2, 14, 4, 5]

CodePudding user response:

You can try this hack as well

from collections import defaultdict
default_value = 0

class points():

  def __init__(self,a1,b1,c1,d1, default_value=default_value):
    self.b1=defaultdict(lambda : default_value, enumerate(b1))
    self.a1=defaultdict(lambda : default_value,enumerate(a1))
    self.c1=defaultdict(lambda : default_value,enumerate(c1))
    self.d1=defaultdict(lambda : default_value,enumerate(d1))


  def plot(self):
    xs=[self.a1[0],self.b1[0],self.c1[0],self.d1[0]]                           
    ys=[self.a1[1],self.b1[1],self.c1[1],self.d1[1]] 
    print(xs)
    print(ys)                           
    colors=['c','m','b','y']

a1=points([1,2],[2],[3,4],[4,5], default_value=default_value)
a1.plot()
  • Related