在下面的代码中,我使用类名将对类变量的引用传递给另一个类中的方法,希望它可以对其进行修改,但事实并非如此。据我了解,Python总是按引用传递参数,而不是按值传递参数,因此我希望类变量的值已更改。为什么不呢?
Python 3.6.7 (v3.6.7:6ec5cf24b7, Oct 20 2018, 12:45:02) [MSC v.1900 32 bit (Intel)] on win32
>>> class Other:
... def modify(self, another_class_member):
... another_class_member += 1
...
>>> class Mine:
... cls_incrementer = 0
... def __init__(self):
... self.my_other = Other()
...
>>> mine = Mine()
>>> mine.cls_incrementer
0
>>> mine.my_other.modify(Mine.cls_incrementer)
>>> Mine.cls_incrementer
0
>>> mine.cls_incrementer
0
答案 0 :(得分:1)
此语句创建一个局部变量并对其进行递增
another_class_member += 1
如果我们打开包装,就会得到
another_class_member = another_class_member + 1
现在应该很清楚,您正在创建一个新的局部变量来隐藏您的参数。
答案 1 :(得分:1)
您无法按照自己的方式做,但是您可以尝试以下操作:
Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class Other:
... def modify(self, another_class):
... another_class.increment()
...
>>> class Mine:
... cls_incrementer = 0
... def __init__(self):
... self.my_other = Other()
... def increment(self):
... self.cls_incrementer += 1
...
>>> mine = Mine()
>>> mine.cls_incrementer
0
>>> mine.my_other.modify(mine)
>>> mine.cls_incrementer
1