【发布时间】:2016-05-20 07:30:14
【问题描述】:
我想创建一个函数,它接收来自同一类的不同对象,然后更改该对象的参数。但是,当我尝试更改该对象时,它不会更改该对象的变量,而是更改本地对象的变量。
例如:
class MyClass():
item = ''
def __init__(self):
self.item = ''
def function(self, otherObject):
otherObject.item = self.item
这是我的代码:
class Taxonomy:
categoryName = ''
itemList = []
def __init__(self, itemList = []):
self.categoryName = categoryName
self.itemList = itemList
def addTaxonomy(self, tax):
self.taxonomy_tree[''][self.categoryName][tax.categoryName]
self.itemList.clear()
self.itemList.append(self.categoryName)
tax.itemList.clear()
出于某种原因,“tax.itemList.clear()”会清除两个 itemList。
【问题讨论】:
-
这应该可以。只要确保你使用
class MyClass(object):(Python 2)或class MyClass:(Python 3)。 -
您需要提供更多上下文:显示对 MyClass().function(...) 的示例调用。
-
第一次编辑时缩进搞混了。我想我已经修好了,但请检查一下以确保我做得正确。 . .
-
这段代码看起来应该像你描述的那样工作。你能举一个它不起作用的例子吗?
-
你不试试看会发生什么?
标签: python function object parameters