简体   繁体   中英

copy list inside function python

I am getting frustrated with this code, I've read some articles, but it seems I wasn't figure it out:

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]

update, I found a rather rogue way:

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]

It is difficult for me to tell what you are trying to do. Let me make some assumption and point a few things out.

Your corrected code:

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

Now you can do what I think you are trying to do:

>>> c=C()          # you need an instance of that object
>>> li=[1,2]
>>> c.a(li)
>>> li
[1, 10]

The attribute k has the same scope as c , so if you want .k to be global make c global:

>>> c.k
10
>>> c.k=22
>>> c.k
22

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM