我发现奇怪的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) 这在Python教程中有介绍,但我还是不太明白Python为什么会有这种风格。是纯粹的约定,还是有一些解释为什么 Python 对默认参数具有以下样式:
我的理解是 Python 更喜欢something=None而不是something=[]函数的默认参数。但是……为什么不使用something=[]?当然这是其他语言的约定,比如 C
以这两个例子为例,它们是等价的
def function(arr, L=[]):
L.append(arr)
return L
Run Code Online (Sandbox Code Playgroud)
和
def function(arr, L=None):
if L is None:
L = []
L.append(arr)
return L
Run Code Online (Sandbox Code Playgroud)
我的理解是,第一个是 Python 的“风格不正确”。为什么?
编辑:啊,我终于明白了。我上面不正确:这两个函数不等价。默认参数在定义函数时计算一次,而不是每次调用函数时!
我想获取列表中嵌套字典的所有键的路径。例如,如果我的字典如下所示
{
"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 中存储len()或值的约定sum()?举个例子,如果你有一个类
class MyClass:
def __init__(self, single_number = 4, multiple_numbers = [1,2,3]):
self.single= single_number
self.multiple = multiple_numbers
def info(self):
print(f"The length of multiple is {len(self.multiple)}")
print(f"The length of multiple is {len(self.multiple)*4}")
print(f"The length of multiple is longer than {len(self.multiple)-1}")
if __name__ == "__main__":
test=MyClass()
test.info()
# other stuff
test.info()
Run Code Online (Sandbox Code Playgroud)
你会在什么时候开始存储len(self.multiple)它自己的价值?值得庆幸的是,python 在len某些任务中for my_numbers in multiple_numbers:不使用 ,所以我不需要它只用于迭代。此外,len对于类的实例, 的值是静态的,并且在运行时的不同部分(可能)多次需要,所以它不是像这里的临时变量 。一般来说,这似乎是(非常少量的)内存与计算之间的权衡。同样的问题适用于sum().
这些问题的一部分是基于意见的,我很高兴听到您的想法,但我主要是在寻找关于此的约定。
len(self.multiple)作为它自己的值存储?length_of_multiple_numbers …