Why does self-attachment not work and how to get around this problem?

I have a class ( dict s list) 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. What for? How to avoid this? With the exception of external sorting, for example:

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

Is it impossible to manipulate the object itself? It is more important 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, is there no way in Python that an object can change itself (not just an instance variable)?

+4
source share
3 answers

You cannot reassign self from a method and expect it to change the external references to an object.

self is just an argument passed to your function. This name indicates an instance of a method call. "Assigning self " is equivalent to:

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

The purpose of self changes what the self name indicates (from one instance of Table to a new instance of Table here). But it is so. It just changes the name (in the scope of your method) and does not affect the base object, but other names (links) pointing to it.


Just do a search using list.sort :

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

Python always passes by value. This means that the purpose of the parameter will never affect the outside of the function. self is just the name you have chosen for one of the options.

+1
source

I was intrigued by this question because I never thought about it. I searched the list.sort code to see how this is done, but apparently this is in C. I think I see what you are getting at; what if there is no super method to call? 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 methods, assign self indices and everything else that is implemented in your class (or that you implement yourself ).

0
source

Source: https://habr.com/ru/post/1500377/


All Articles