简体   繁体   中英

How to define default list in python class

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?

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]

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM