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

前端 未结 3 552
南旧
南旧 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:46

    You can't re-assign to self from within a method and expect it to change external references to the object.

    self is just an argument that is passed to your function. It's a name that points to the instance the method was called on. "Assigning to self" is equivalent to:

    def fn(a):
       a = 2
    a = 1
    fn(a)
    # a is still equal to 1
    

    Assigning to self changes what the self name points to (from one Table instance to a new Table instance here). But that's it. It just changes the name (in the scope of your method), and does affect not the underlying object, nor other names (references) that point to it.


    Just sort in place using list.sort:

    def sort(self, in_col_name):
        super(Table, self).sort(key=lambda x: x[in_col_name])
    

提交回复
热议问题