Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does this function not fire in the __init__ method?

Tags:

python

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?

like image 533
user1131308 Avatar asked Nov 29 '22 03:11

user1131308


2 Answers

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.

like image 100
NPE Avatar answered Dec 17 '22 22:12

NPE


The documentation states it pretty clearly:

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

like image 41
unwind Avatar answered Dec 17 '22 22:12

unwind