【问题标题】:Is it possible to call variables of a different object of the same class in Python?是否可以在 Python 中调用同一类的不同对象的变量?
【发布时间】: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


【解决方案1】:

因为itemList 都指向同一个列表实例。在 python 中,使用可变类型创建默认参数值并不是一个好主意。采取def f(x=[]): pass。对于没有传递参数 x 的所有 f 调用,此函数共享相同的列表。

这段代码更好地说明了我想说的。

def f(x=[]):
    x.append(1)
    return x

f()
print f() # ouput: [1, 1]

希望您可以使用默认的 None 值轻松重构参数。

def f(x=None):
    x = x or []
    x.append(1)
    return x

f()
print f() # ouput: [1]

您的问题的具体解决方案是:

def __init__(self,  itemList = None):
     self.categoryName = categoryName
     self.itemList = itemList or [] 

【讨论】:

    猜你喜欢
    • 2017-02-13
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 2012-08-22
    相关资源
    最近更新 更多