Why does assigning to self not work, and how to work around the issue?

前端 未结 3 554
南旧
南旧 2020-12-11 21:04

I have a class (list of dicts) and I want it to sort itself:

class Table(list):
…
  def sort (self, in_col_name):
    self = Table(sorted(self,          


        
3条回答
  •  执笔经年
    2020-12-11 21:35

    I was intrigued by this question because I had never thought about this. I looked for the list.sort code, to see how it's done there, but apparently it's in C. I think I see where you're getting at; what if there is no super method to invoke? Then you can do something like this:

    class Table(list):
        def pop_n(self, n):
            for _ in range(n):
                self.pop()
    
    >>> a = Table(range(10))
    >>> a.pop_n(3)
    >>> print a
    [0, 1, 2, 3, 4, 5, 6]
    

    You can call self's methods, do index assignments to self and whatever else is implemented in its class (or that you implement yourself).

提交回复
热议问题