你如何在__init__中调用类的方法?

Noo*_*bot 4 python constructor

码:

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
Run Code Online (Sandbox Code Playgroud)

预期结果

bar!!!
Run Code Online (Sandbox Code Playgroud)

实际结果

bar
Run Code Online (Sandbox Code Playgroud)

你如何在init中调用类的方法?

Ash*_*ary 5

修改self.z,而不是inp:

def my_function(self, inp):
    self.z += '!!!'
Run Code Online (Sandbox Code Playgroud)

其次字符串在python中是不可变的,因此修改inp不会影响原始字符串对象.

看看self.z可变对象时会发生什么:

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

C()        
Run Code Online (Sandbox Code Playgroud)

输出:

['!', '!', '!']
['!', '!', '!']
Run Code Online (Sandbox Code Playgroud)