可能重复:
Python中的"最小惊讶":可变默认参数
我正在尝试从"fooclass"类创建一个具有不同属性的对象列表,但总是最终得到包含相同值的列表中的所有元素.
这是我运行的代码:
#!/usr/bin/env python
class fooclass():
def __init__(self,vertices = [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]):
self.vertices = vertices
l=[]
print(l)
a=fooclass(); a.vertices[0]=[7,9,9]; l.append(a)
print 'a=', a.vertices
a=fooclass(); a.vertices[0]=[789,9,9]; l.append(a)
print 'a=', a.vertices
print(l[0].vertices)
print(l[1].vertices)
print(l)
l=[]
print(l)
a=fooclass(); a.vertices[0]=[7,9,9]; l.append(a)
print 'a=', a.vertices
b=fooclass(); b.vertices[0]=[789,9,9]; l.append(b)
print 'b=', b.vertices
print(l[0].vertices)
print(l[1].vertices)
print(l[0])
print(l[1])
Run Code Online (Sandbox Code Playgroud)
我得到的输出:
$ python ./class_test2.py
[]
a= [[7, 9, 9], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] …Run Code Online (Sandbox Code Playgroud) 我最近阅读了objgraph文档,我对以下代码感到困惑
>>> class MyBigFatObject(object):
... pass
...
>>> def computate_something(_cache={}):
... _cache[42] = dict(foo=MyBigFatObject(),
... bar=MyBigFatObject())
... # a very explicit and easy-to-find "leak" but oh well
... x = MyBigFatObject() # this one doesn't leak
Run Code Online (Sandbox Code Playgroud)
它表明"非常明显且容易找到'泄漏'".这有内存泄漏吗?这是dict _cache吗?
我发现奇怪的Python的行为(或者我可能不明白属性的继承和/或默认值是如何工作的).
对于给定的代码
class A(object):
def __init__(self, s):
self.s = s
print "in init", self.s
class B(A):
def __init__(self, s = set()):
super(B, self).__init__(s)
print "after super", self.s
self.s.add('foo')
print '--------------'
if __name__ == "__main__":
a = B()
b = B()
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
in init set([])
after super set([])
--------------
in init set(['foo']) # Why it has value set in other object?!
after super set(['foo'])
--------------
Run Code Online (Sandbox Code Playgroud)
当然,期望的行为是使用空集在第二个对象(b)中初始化self,但由于未知原因,它从前一个对象获取状态.为什么会这样?如何获得理想的行为?
谢谢!
我一直尝试使用 dict.keys 从我的字典中获取键列表,但它一直给我:
def reverse(PB = {'l': 3, 'y':1, 'u':2}):
print(PB.keys())
印刷:
dict_keys(['u', 'l', 'y'])
在我拥有 2.7 以上的 python 版本之前,我从未遇到过这个问题...有什么想法吗?
我有这样的代码:
import random
def helper():
c = random.choice([False, True]),
d = 1 if (c == True) else random.choice([1, 2, 3])
return c, d
class Cubic(object):
global coefficients_bound
def __init__(self, a = random.choice([False, True]),
b = random.choice([False, True]),
(c, d) = helper()):
...
...
Run Code Online (Sandbox Code Playgroud)
引入了helper()函数,因为我在函数本身的定义中没有共同依赖的参数 - Python抱怨它在计算d时找不到c.
我希望能够像这样创建这个类的对象,更改默认参数:
x = Cubic(c = False)
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误:
Traceback (most recent call last):
File "cubic.py", line 41, in <module>
x = Cubic(c = False)
TypeError: __init__() got an unexpected keyword argument 'c'
Run Code Online (Sandbox Code Playgroud)
这可能与我写的方式有关吗?如果没有,我应该怎样做?
我是python的新手.
我打电话时为什么没有收到新物品tempMyObject = myObject()?
class myObject(object):
x = []
def getMyObject():
tempMyObject = myObject()
print "debug: %s"%str(tempMyObject.x)
tempMyObject.x.append("a")
return tempMyObject
#run
a = getMyObject()
b = getMyObject()
Run Code Online (Sandbox Code Playgroud)
我的调试打印出来:
debug: []
debug: ["a"]
Run Code Online (Sandbox Code Playgroud)
我不明白为什么这两个调试数组都不为null,有人可以赐教吗?
编辑:我发现我的帖子中放入python代码的错误.我在我的函数中使用.append("a")
我在使用Python从文件导入数据时遇到了一些问题.我是Python的新手,所以我的错误可能很简单.
我正在阅读3列,制表符分隔的文本文件,没有标题.我正在使用三个不同的数据文件创建3个数据文件实例.
我可以看到每个对象都引用了不同的内存位置,因此它们是分开的.
当我查看存储在每个实例中的数据时,每个实例都具有相同的内容,包括彼此附加的三个数据文件.
我做错了什么?
读入数据的类是:
class Minimal:
def __init__(self, data=[]):
self.data = data
def readFile(self, filename):
f = open(filename, 'r')
for line in f:
line = line.strip()
columns = line.split()
#creates a list of angle, intensity and error and appends it to the diffraction pattern
self.data.append( [float(columns[0]), float(columns[1]), float(columns[2])] )
f.close()
def printData(self):
for dataPoint in self.data:
print str(dataPoint)
Run Code Online (Sandbox Code Playgroud)
数据文件看起来像:
1 4 2
2 5 2.3
3 4 2
4 6 2.5
5 8 5
6 10 3
Run Code Online (Sandbox Code Playgroud)
我用来实际创建Minimal实例的程序是: …
class abc :
x = 10
list = []
def __init__(self):
self.a = 30
self.b = 40
a = abc()
b = abc()
a.x = a.x + 1
print a.x
print b.x
a.list.append(1)
print b.list
Output :
10
11
[1]
Run Code Online (Sandbox Code Playgroud)
所以我们看到它x不是跨对象共享的a,b而是list共享的.有人可以解释这种行为吗?
所以它的答案似乎在于列表是可变的objs而数字不是:
class abc :
x = 10
m_list = []
def __init__(self):
self.a = 30
self.b = 40
a = abc()
b = abc()
print id(a.x)
a.x = a.x + 1 …Run Code Online (Sandbox Code Playgroud) 我想获取列表中嵌套字典的所有键的路径。例如,如果我的字典如下所示
{
"persons": [{
"id": "f4d322fa8f552",
"address": {
"building": "710",
"coord": "[123, 465]",
"street": "Avenue Road",
"zipcode": "12345"
},
"cuisine": "Chinese",
"grades": [{
"date": "2013-03-03T00:00:00.000Z",
"grade": "B",
"score": {
"x": 3,
"y": 2
}
}, {
"date": "2012-11-23T00:00:00.000Z",
"grade": "C",
"score": {
"x": 1,
"y": 22
}
}],
"name": "Shash"
}]
}
Run Code Online (Sandbox Code Playgroud)
我想获得
path = [['persons'], ['persons','id'],['persons','address'],['persons','address','building']...]直到最后一个键的路径。
我尝试遍历整个字典来附加路径变量。试图从打印 python 嵌套字典的所有值的完整键路径中获得一些灵感,但我无法获取列表内的路径。
还有其他可能的方法来实现这一点吗?
我想在函数内定义一个字典。我如何一次只能在函数创建时定义该词典。我试图防止在每个函数调用上创建字典。目前,我定义了一个全局字典并在函数内部使用它,但是还有其他解决方案吗?
media_types = {
1: 'New Video',
2: 'New Image',
3: 'New File',
}
def get_media_type(t):
return media_types.get(t, None)
Run Code Online (Sandbox Code Playgroud) python ×9
dictionary ×2
key ×2
python-3.x ×2
class ×1
inheritance ×1
list ×1
memory-leaks ×1
objgraph ×1
oop ×1