user1131308
user1131308

Reputation: 309

why does this function not fire in the __init__ method?

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

Why doesn't lower() operate on the contents of val in this code?

Upvotes: 4

Views: 169

Answers (4)

Tadeck
Tadeck

Reputation: 137290

It is because strings are immutable. You cannot change them in-place.

Thus, you must overwrite the value of the variable like that:

self.val = self.val.lower()

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

Example of mutable object with 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?

Upvotes: 2

Melug
Melug

Reputation: 1031

In Python there are 2 types of function that leads to this kind of confusion. For example to sort a list you could do:

>>> a.sort()

or

>>> a = sorted(a)

first one sorts in "a", but second sorts "a" and returns new sorted list.

Upvotes: 0

unwind
unwind

Reputation: 399703

The documentation states it pretty clearly:

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

Upvotes: 5

NPE
NPE

Reputation: 500157

You probably mean:

self.val = self.val.lower()

Or, more concisely:

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

To elaborate, lower() doesn't modify the string in place (it can't, since strings are immutable). Instead, it returns a copy of the string, appropriately modified.

Upvotes: 15

Related Questions