' STR'对象没有属性' n'

时间:2015-08-23 20:53:00

标签: python class python-2.7 attributes

我在python中遇到错误:

文件" C:\ Users \ user \ workspace \ LINKAGE \ 2.py",第13行, init self.n = points [0] .n AttributeError:' str'对象没有属性' n'

这个错误意味着什么?我做错了什么?

python代码是:

import math,sys

class Cluster:

    points = []
    elem = int(raw_input("how many points do you want to cluster?"))
    for i in range(0, elem):
        points.append(raw_input("Enter next point :"))
        print points

    def __init__(self, points):
        self.points= points
        self.n = points[0].n 

        for p in points:
            if p.n != self.n: raise Exception("ILLEGAL: MULTISPACE CLUSTER")

    # Return a string representation of this Cluster
    def __repr__(self):
        return str(self.points)


    # Return the single-linkage distance between this and another Cluster
    def getSingleDistance(self, cluster):
        ret = getDistance(self.points[0], cluster.points[0])
        for p in self.points:
            for q in cluster.points:
                distance = getDistance(p, q)
                if distance < ret: ret = distance
        return ret
    # Return the complete-linkage distance between this and another Cluster
    def getCompleteDistance(self, cluster):
        ret = getDistance(self.points[0], cluster.points[0])
        for p in self.points:
            for q in cluster.points:
                distance = getDistance(p, q)
                if distance > ret: ret = distance
        return ret
    # Return the centroid-linkage distance between this and another Cluster

    def fuse(self, cluster):
        # Forbid fusion of Clusters in different spaces
        if self.n != cluster.n: raise Exception("ILLEGAL FUSION")
        points = self.points
        points.extend(cluster.points)
        return Cluster(points) 


# -- Return a distance matrix which captures distances between all Clusters
def makeDistanceMatrix(clusters, linkage):
    ret = dict()
    for i in range(len(clusters)):
        for j in range(len(clusters)):
            if j == i: break
            if linkage == 's':
                ret[(i,j)] = clusters[i].getSingleDistance(clusters[j])
            elif linkage == 'c':
                ret[(i,j)] = clusters[i].getCompleteDistance(clusters[j])
            else: raise Exception("INVALID LINKAGE")
    return ret
# -- Return Clusters of Points formed by agglomerative clustering

def agglo(points, linkage, cutoff):
    # Currently, we only allow single, complete, or average linkage
    if not linkage in [ 's', 'c' ]: raise Exception("INVALID LINKAGE")
    # Create singleton Clusters, one for each Point
    clusters = []
    for p in points: clusters.append(Cluster([p]))
    # Set the min_distance between Clusters to zero
    min_distance = 0
    # Loop until the break statement is made
    while (True):
        # Compute a distance matrix for all Clusters
        distances = makeDistanceMatrix(clusters, linkage)
        # Find the key for the Clusters which are closest together
        min_key = distances.keys()[0]
        min_distance = distances[min_key]
        for key in distances.keys():
            if distances[key] < min_distance:
                min_key = key
                min_distance = distances[key]
        # If the min_distance is bigger than the cutoff, terminate the loop
        # Otherwise, agglomerate the closest clusters
        if min_distance > cutoff or len(clusters) == 1: break
        else:
            c1, c2 = clusters[min_key[0]], clusters[min_key[1]]
            clusters.remove(c1)
            clusters.remove(c2)
            clusters.append(c1.fuse(c2))
    # Return the list of Clusters
    return clusters
# -- Get the Euclidean distance between two Points
def getDistance(a, b):
    # Forbid measurements between Points in different spaces
    if a.n != b.n: raise Exception("ILLEGAL: NON-COMPARABLE POINTS")
    # Euclidean distance between a and b is sqrt(sum((a[i]-b[i])^2) for all i)
    ret = 0.0
    for i in range(a.n):
        ret = ret+pow((a.coords[i]-b.coords[i]), 2)
    return math.sqrt(ret)
# -- Create a random Point in n-dimensional space

# -- Plot Clusters using Tkinter
def plot(clusters):
    root = Tk()
    cp = ClusterPlot(root)
    root.mainLoop()
# -- Main function
def main(args):
    linkage, agglo_cutoff = 's', 150.0
    points = Cluster.points
    # Create num_points random Points in n-dimensional space, print them
    print "\nPOINTS:"
    # Cluster the points using the agglomerative algorithm, print the results
    clusters = agglo( points, linkage, agglo_cutoff)
    print "\nAGGLOMERATIVE\nCLUSTERS:"
    for c in clusters: print "C:", c

if __name__ == "__main__": main(sys.argv)     

1 个答案:

答案 0 :(得分:0)

这可能是因为points是一个列表。因此,当您使用points[0]时,它会调用列表中的第一个项目,该项目应该是一个字符串。例如:

srtings = ['hello']
print strings[0]          #returns hello, which is a string

现在.n中的points.n表示points是一个函数,它可以包含一个名为n的变量,如果您调用points.n可以使用它。但事实并非如此,这是一份清单。由于列表永远不会有任何属性,points.n将始终引发错误,因为points不是函数(另一个时间是函数中未定义n) 。例如,可以在没有错误的情况下调用points.n

def points():
    n = []    #You could get an item out of the list by calling points.n[x]