Why does this function not work in the __init__ method?

class test: def __init__(self, val): self.val = val self.val.lower() 

Why doesn't the bottom () work with the contents of val in this code?

+4
source share
4 answers

You probably mean:

 self.val = self.val.lower() 

Or, more briefly:

 class test: def __init__(self, val): self.val = val.lower() 

To clarify, lower() does not change the string in place (it cannot, since the strings are immutable). Instead, it returns a copy of the string appropriately modified.

+15
source

The documentation reads:

Return a copy of the string with all circled characters [4] converted to lowercase.

+5
source

This is because strings are immutable . You cannot change them locally.

Therefore, you should overwrite the value of the variable as follows:

 self.val = self.val.lower() 

Note. Unless, of course, your self.val not a string, but rather some mutable object that changes in place after the lower() method is called. But this is not the case (you can do it if you created the self.val class, though).

An example of a mutable object with the lower() method changing it in place:

 >>> class LowerableList(list): def lower(self): for i, item in enumerate(self): self[i] = item.lower() >>> a = LowerableList(['A', 'a', 'X', 'D']) >>> a ['A', 'a', 'X', 'D'] >>> a.lower() >>> a ['a', 'a', 'x', 'd'] 

Does it help?

+2
source

In Python, there are 2 types of functions that lead to such confusion. For example, to sort a list you could make:

 >>> a.sort() 

or

 >>> a = sorted(a) 

first sorts to "a", and the second sorts to "a" and returns a new sorted list.

0
source

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


All Articles