1

以下のコードでは、文字列 '1/2/3/4/5/6/' を階層ツリーに解析しようとしています。出力は次のようになるはずです。

# 1 -> 2 
# 2 -> 3
# 3 -> 4
# 4 -> 5
# 5 -> 6

しかし、それは返します:

# 1 -> [2, 3, 4, 5, 6]

いくつかの変数を出力した後、変数「a1」は最初の「a1」だけでなく、「a1」という名前のすべての変数、すべての呼び出しメソッドを表し、「a1」変数を生成し、操作する理由を見つけましたそれ。Python は他の OO 言語が好きではありません。'a1' は現在呼び出し専用の唯一の変数であると予想されます。私の質問は、Python でこの種の問題を解決する最善の方法は何ですか?

class A(object):
    name = ''
    children = []

    def __repr__(self):
        return '%s -> %s' % (self.name, self.children)

def recurse(a1, s):
    if len(s) == 0: return

    s1 = s[0:s.find('/')]
    a1.name = s1
    print 's1: %s' % (s1)

    s2 = s[s.find('/') + 1:]
    print 's2: %s' % (s2)

    a2 = A()
    a1.children.append(a2) # Problem: why all child append into variable 'a' and all children too?
    # print 'locals() -> ', locals()    when I print locals(), I got the reason, but what's the best way to fix the problem?
    recurse(a2, s2)

a = A()
recurse(a, '1/2/3/4/5/6/') # input string required to ends with '/'

# expect: 
# 1 -> 2 
# 2 -> 3
# 3 -> 4
# 4 -> 5
# 5 -> 6

print a
4

2 に答える 2

4

子はクラス属性であるため、すべてのインスタンスが同じリストを共有および変更します

class A(object): 
    name = ''                      # these are class
    children = []                  # attributes

各インスタンスに独自のリストを与える必要があります

class A(object):
    def __init__(self):
        self.name = ''             # these are instance
        self.children = []         # attributes
于 2013-06-03T02:49:19.263 に答える