1

I want to construct a class to flatten a python list. I can make it by defining function like this;

liste=[[1,2],3,[4],[[5],6]]

flatLIST=[]

def recur(a):

    if (type(a)==list):
        for i in a:
           recur(i)
    else:
        flatLIST.append(a)

recur(liste)
flatLIST

[1, 2, 3, 4, 5, 6]

But when i cannot achieve it by constructing a class.

class flatYVZ():

    def __init__(self,liste):
        self.flatLIST=[]
        recur(liste)

    def recur(self,a):

        if (type(a)==list):
            for i in a:
                recur(i)
        else:
            self.flatLIST.append(a)

    def flatting(self):        
        self.sonuc=self.flatLIST

example=[[1,2],3,[4],[[5],6]]
objec=flatYVZ(example)
objec.sonuc

[]

yvz demir
  • 13
  • 3

1 Answers1

0

You need to reference self, or you'll call the function you defined previously, not your class method.

Here you need to change recur(liste) to self.recur(liste) in __init__ and recur(i) to self.recur(i) in recur(self, a).

class flatYVZ():

    def __init__(self,liste):
        self.flatLIST=[]
        self.recur(liste)

    def recur(self,a):

        if (type(a)==list):
            for i in a:
                self.recur(i)
        else:
            self.flatLIST.append(a)

    def flatting(self):        
        self.sonuc=self.flatLIST

example=[[1,2],3,[4],[[5],6]]
objec=flatYVZ(example)
print(objec.flatLIST)
geofurb
  • 489
  • 4
  • 13