Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

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

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, key=lambda x: x[in_col_name]))

but it doesn't work at all. Why? How to avoid it? Except for sorting it externally, like:

new_table = Table(sorted(old_table, key=lambda x: x['col_name'])

Isn't it possible to manipulate the object itself? It's more meaningful to 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, I think, works. And in general, isn't there any way in Python which an object is able to change itself (not only an instance variable)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...