Python构造函数怪诞

2024-04-25 06:09:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的代码:

class bfs:
    vis=[]
    bags=[]
    def __init__ (self,x): 
        for i in p:    #initializes vis with len(p) zeroes 
            self.vis.append(0)
            print self.vis
        self.vis[x]=1   #marks index x as visited
        print self.vis

p=raw_input("Input values: ").split()
for i in range(0,len(p)):
    p[i]=int(p[i])

q=[]
for i in range(0,len(p)):
    q.append(bfs(i))

print
for i in q:
    print i.vis

如果我输入,比如说,任何3个数字,为什么我得到这个输出:

[0]
[0, 0]
[0, 0, 0]
[1, 0, 0]
[1, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 0, 0, 0, 0]
[1, 1, 1, 0, 0, 0, 0, 0, 0]

[1, 1, 1, 0, 0, 0, 0, 0, 0]
[1, 1, 1, 0, 0, 0, 0, 0, 0]
[1, 1, 1, 0, 0, 0, 0, 0, 0]

而不是像这样?你知道吗

[0]
[0, 0]
[0, 0, 0]
[1, 0, 0]
[0]
[0, 0]
[0, 0, 0]
[0, 1, 0]
[0]
[0, 0]
[0, 0, 0]
[0, 0, 1]

[1, 0, 0]
[0, 1, 0]
[0, 0, 1]

该程序似乎只是继续在所有创建的obj中使用一个数组。我不明白为什么。任何帮助都是巨大的。你知道吗


Tags: 代码inselfforleninitdefrange
1条回答
网友
1楼 · 发布于 2024-04-25 06:09:18

问题是您将visbags定义为类的一部分(作为“属性引用”),而不是在构造函数中。请尝试以下操作:

class bfs:
    def __init__(self, x):
        self.vis = []
        self.bags = []
        # etc.

documentation for class objects可能有助于:

Attribute references use the standard syntax used for all attribute references in Python: obj.name. Valid attribute names are all the names that were in the class’s namespace when the class object was created. So, if the class definition looked like this:

class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        return 'hello world'

then MyClass.i and MyClass.f are valid attribute references, returning an integer and a function object, respectively. Class attributes can also be assigned to, so you can change the value of MyClass.i by assignment.

关于这个还有一个Dive Into Python page

Class attributes are available both through direct reference to the class and through any instance of the class.

Note: In Java, both static variables (called class attributes in Python) and instance variables (called data attributes in Python) are defined immediately after the class definition (one with the static keyword, one without). In Python, only class attributes can be defined here; data attributes are defined in the __init__ method.

相关问题 更多 >