BING
BING

Reputation: 25

TypeError: object of type '~~~~' has no len()

I have one quick question, regarding why object of type "~~~" no len()

X_train=np.array([[5,4],
                  [4,5],
                  [4,4],
                  [6,-6]])
class MyKNN:
    def __init__(self, k):
        self.k = k

    def Build_KDTree(data, depth = 0):
        n = len(data)
        return n

 knn = MyKNN(3)
 knn.Build_KDTree(X_train)

This code give me TypeError: object of type 'MyKNN' has no len(), which confuse me very very much. If I build a function as:

 def Build_KDTree(data):
     n = len(data)
     return n

 Build_KDTree(X_train)

It works! May I know what kind of theory behind of such phenomenon?

Thank you so much

Upvotes: 1

Views: 3655

Answers (2)

AnthonyHein
AnthonyHein

Reputation: 131

Fixed, you were missing the self argument.


import numpy as np

X_train=np.array([[5,4], [4,5], [4,4], [6,-6]])

class MyKNN:
    def __init__(self, k):
        self.k = k

    def Build_KDTree(self, data, depth = 0):
        n = len(data)
        return n

knn = MyKNN(3)
knn.Build_KDTree(X_train)

Upvotes: 1

Raiyan Chowdhury
Raiyan Chowdhury

Reputation: 311

You're missing the self parameter in Build_KDTree. The 'theory' behind this is simply that Python uses the first parameter in a method as a reference to the object. The variable 'self' is just best programming practice, however in Python any variable can be used to replace self. To fix this issue simply add the self parameter:

X_train=np.array([[5,4],
                  [4,5],
                  [4,4],
                  [6,-6]])
class MyKNN:
    def __init__(self, k):
        self.k = k

    def Build_KDTree(self, data, depth = 0):
        n = len(data)
        return n

 knn = MyKNN(3)
 knn.Build_KDTree(X_train)

Upvotes: 0

Related Questions