python - Why does assigning to self not work, and how to work around the issue? -
i have class (list of dict
s) , want sort itself:
class table(list): … def sort (self, in_col_name): self = table(sorted(self, key=lambda x: x[in_col_name]))
but doesn't work @ all. why? how avoid it? except sorting externally, like:
new_table = table(sorted(old_table, key=lambda x: x['col_name'])
isn't possible manipulate object itself? it's more meaningful have:
class table(list): pass
than:
class table(object): l = [] … def sort (self, in_col_name): self.l = sorted(self.l, key=lambda x: x[in_col_name])
which, think, works. , in general, isn't there any way in python object able change (not instance variable)?
you can't re-assign self
within method , expect change external references object.
self
argument passed function. it's name points instance method called on. "assigning self
" equivalent to:
def fn(a): = 2 = 1 fn(a) # still equal 1
assigning self
changes self
name points (from 1 table
instance new table
instance here). that's it. changes name (in scope of method), , affect not underlying object, nor other names (references) point 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])
Comments
Post a Comment