Home > Software engineering >  Get all the strings out of a created class
Get all the strings out of a created class

Time:11-08

I have a class as declared like so:

class StringHolder(object):

    str_a = None
    str_b = None

    def __init__(self, str_a, str_b):

        self.str_a = str_a
        self.str_b = str_b

I hold all the objects in a list:

holder: List[StringHolder] = []

holder.append(StringHolder("a", "x"))
holder.append(StringHolder("a", "y"))
holder.append(StringHolder("a", "z"))

holder.append(StringHolder("b", "x"))
holder.append(StringHolder("b", "y"))
holder.append(StringHolder("b", "z")

I want to get a List[str] of all the str_a used. I don't care about duplicates as I can do list(set(theList)) to get a unique copy. Do I have to adapt my class at all?

CodePudding user response:

please try this:

class StringHolder(object):

    str_a = None
    str_b = None

    def __init__(self, str_a, str_b):   
        self.str_a = str_a
        self.str_b = str_b

holder =[]

holder.append(StringHolder("a", "x"))
holder.append(StringHolder("a", "y"))
holder.append(StringHolder("a", "z"))

holder.append(StringHolder("b", "x"))
holder.append(StringHolder("b", "y"))
holder.append(StringHolder("b", "z"))
lis = []
for x in holder:
  lis.append(x.str_a)
print(set(lis))

CodePudding user response:

Do you try something which is as like below:

class StringHolder(object):

    str_a = []
    str_b = []

    def __call__(self, str_a, str_b):
        self.str_a.append(str_a)
        self.str_b.append(str_b)

holder = StringHolder() 
holder("a", "x")
holder("a", "y")
holder("a", "z")

holder("b", "x")
holder("b", "y")
holder("b", "z")

print(holder.str_a)

  • Related