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中调用类的方法?
修改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)
| 归档时间: |
|
| 查看次数: |
135 次 |
| 最近记录: |