我对这段代码感到沮丧,我读过一些文章,但似乎我没弄明白:
class c:
def __init__(self):
self.k = [9, 8]
def a(x):
k = c()
x = k.k
l = [1, 9]
a(l)
print l # expects [9, 8], got [1, 9]
更新,我发现了一种相当流氓的方式:
class c:
def __init__(self):
self.k = [9, 8]
def a(x):
k = c()
for i in reversed(x):
x.remove(i)
for i in k.k:
x.append(i)
l = [1, 9]
a(l)
print l # output [9, 8]
答案 0 :(得分:3)
我很难说出尝试要做什么。让我做一些假设并指出一些事情。
您的更正代码:
class C: # by convention, Python classes are capitalized...
def __init__(self):
self.k = 10
def a(self, x): # you need 'self' to refer to what instance
x[1] = self.k
现在你可以做我想做的事情:
>>> c=C() # you need an instance of that object
>>> li=[1,2]
>>> c.a(li)
>>> li
[1, 10]
属性k
与c
具有相同的范围,因此如果您希望.k
为全局,请c
全局:
>>> c.k
10
>>> c.k=22
>>> c.k
22