相关疑难解决方法(0)

Python中的旧样式和新样式类有什么区别?

Python中的旧样式和新样式类有什么区别?我什么时候应该使用其中一种?

python oop types class new-style-class

953
推荐指数
8
解决办法
22万
查看次数

Python范围/静态误解

我真的坚持为什么下面的代码块1导致输出1而不是输出2?

代码块1:

class FruitContainer:
       def __init__(self,arr=[]):
           self.array = arr
       def addTo(self,something):
           self.array.append(something)
       def __str__(self):
           ret = "["
           for item in self.array:
               ret = "%s%s," % (ret,item)
           return "%s]" % ret

arrayOfFruit = ['apple', 'banana', 'pear']
arrayOfFruitContainers = []

while len(arrayOfFruit) > 0:
   tempFruit = arrayOfFruit.pop(0)
   tempB = FruitContainer()
   tempB.addTo(tempFruit)
   arrayOfFruitContainers.append(tempB)

for container in arrayOfFruitContainers:
   print container 

**Output 1 (actual):**
[apple,banana,pear,]
[apple,banana,pear,]
[apple,banana,pear,]

**Output 2 (desired):**
[apple,]
[banana,]
[pear,]
Run Code Online (Sandbox Code Playgroud)

此代码的目标是迭代数组并将每个数据包装在父对象中.这是我的实际代码的减少,它将所有苹果添加到一袋苹果等等.我的猜测是,出于某种原因,它要么使用相同的对象,要么就像水果容器使用静态数组一样.我不知道如何解决这个问题.

python iteration scope class static-members

6
推荐指数
2
解决办法
493
查看次数

Python对象初始化错误.或者我误解了对象是如何工作的?

  1 import sys
  2 
  3 class dummy(object):
  4     def __init__(self, val):
  5         self.val = val
  6 
  7 class myobj(object):
  8     def __init__(self, resources):
  9         self._resources = resources
 10 
 11 class ext(myobj):
 12     def __init__(self, resources=[]):
 13         #myobj.__init__(self, resources)
 14         self._resources = resources
 15 
 16 one = ext()
 17 one._resources.append(1)
 18 two = ext()
 19 
 20 print one._resources
 21 print two._resources
 22 
 23 sys.exit(0)
Run Code Online (Sandbox Code Playgroud)

这将打印的参考对象分配one._resources两个onetwo对象.我认为这two将是一个空数组,因为如果在创建对象时没有定义它,它就会明确地设置它.取消注释也会myobj.__init__(self, resources)做同样的事情.使用super(ext, self).__init__(resources)也做同样的事情.

我可以使用它的唯一方法是使用以下方法:

two …
Run Code Online (Sandbox Code Playgroud)

python arguments mutable

1
推荐指数
2
解决办法
242
查看次数