Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you call a class' method in __init__?

Code:

class C:
    def __init__(self, **kwargs):
        self.w = 'foo'
        self.z = kwargs['z']
        self.my_function(self.z)    
    def my_function(self, inp):
        inp += '!!!'

input_args = {}
input_args['z'] = 'bar'
c = C(**input_args)
print c.z

Expected Result

bar!!!

Actual Result

bar

How do you call a class' method in init?

like image 733
Noob Saibot Avatar asked Feb 16 '23 23:02

Noob Saibot


1 Answers

Modify self.z, not inp:

def my_function(self, inp):
    self.z += '!!!'

Secondly strings are immutable in python, so modifying inp won't affect the original string object.

See what happens when self.z is mutable object:

class C:
    def __init__(self, ):
        self.z = []
        self.my_function(self.z)    
    def my_function(self, inp):
        inp += '!!!'
        print inp
        print self.z

C()        

output:

['!', '!', '!']
['!', '!', '!']
like image 85
Ashwini Chaudhary Avatar answered Feb 18 '23 14:02

Ashwini Chaudhary