Different behaviour for class static attributes



  • Why does a class static attribute differently to pandas? Maybe I'm fascinating, but this behavior doesn't make sense.

    class test:
        table=[]
        def __init__(self,count):
            self.a=count
    
    def changer(self):
        self.a+=1
        self.table=self.table.append(self.a)
    

    class test2:
    table=pd.DataFrame()
    def init(self,count):
    self.a=count

    def changer(self):
        self.a+=1
        self.table=self.table.append({self.a:self.a},ignore_index=True)
    

    for i in [1,2,3]:
    i=test(i)
    i.changer()
    print(test.table)

    for i in [5,6,7]:
    i=test2(i)
    i.changer()
    print(test2.table)

    In the first case, the statistical attribute of the list and print(test.table) constituent constituent.[2,3,4]
    In the second case of the pandas object, where the rows are fast added, but the result of the empty data has been reached. What's the reason for this weird behavior and how better it goes?



  • If you add. print(self.table) both methods changerYou'll be expected to have some surprise. Suddenly they find out self.table Once it's given a new meaning, it's a very separate substance. class.table and first class self.table after the attribution, the value None

    However, self.table.append If the list is filled class.tableWhich makes sense, because for the list. .append Works. in place and adds values to the list to which reference is made class.tableHere you go. Pandas That's not gonna happen because there's a trick table.append doesn't add anything to the existing table, but creates a new one.

    But I can tell you a way to work in the case. Pandas♪ That's why we have to change the initialization of the class. test2 and method changer:

    class test2:
        table=pd.DataFrame({0: [0]}) # делаем одну колонку с одним значением
        def __init__(self,count):
            self.a=count
    
    def changer(self):
        self.a+=1
        self.table[self.a] = self.a # пишем новое значение в исходный DataFrame
    

    Conclusion:

    [2, 3, 4]
    0 6 7 8
    0 0 6 7 8

    Although it is true, it is possible not to change initialization, but to do so in changer:

        def changer(self):
    self.a+=1
    self.table.loc[0, self.a] = self.a

    But the result will be float:

    [2, 3, 4]
    6 7 8
    0 6.0 7.0 8.0



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2