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

标签 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

预期结果

bar!!!

实际结果

bar

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

最佳答案

修改self.z,而不是inp:

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

其次,字符串在 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()        

输出:

['!', '!', '!']
['!', '!', '!']

关于python - 你如何在 __init__ 中调用类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17598914/

相关文章:

python - 如何获取 sqlalchemy 中级联删除(或标记为删除)项目的 ID?

java - Java中是否可以为接口(interface)创建注释,强制实现类的构造函数的特定参数列表

c# - 创建构造函数时报错 "member names cannot be the same as their enclosing type"是什么意思,如何解决?

c++ - 类层次结构中的约束构造函数,C++

C++ - 创建安全的 const char* 构造函数

For 循环中的 Python 列表

python - 在可迭代中获取一个元素和以下元素的优雅/高效方法

python - 为什么 Python 不能识别我的 utf-8 编码源文件?

python - 类型错误 : expected string or bytes-like object

java - 为什么优先级队列构造函数会占用比较器的容量?