Reputation: 37
How to call the __len__()
function using an object of the class ?
class foo(object):
def __init__(self,data)
self.data = data
def __len__(self):
return len(self.data)
x = foo([1,2,3,4])
Upvotes: 1
Views: 683
Reputation: 2993
len()
.Imagine you have only:
class foo(object):
def __init__(self,data):
self.data = data
x = foo([1,2,3,4])
print(len(x))
Now, if you have:
class foo(object):
def __init__(self,data):
self.data = data
self.length = len(data)
x = foo([1,2,3,4])
print(len(x))
(You can get the length with x.length
though)
But if you add the magical method __len__()
:
class foo(object):
def __init__(self,data):
self.data = data
self.length = len(data)
def __len__(self):
return self.length
x = foo([1,2,3,4])
print(len(x))
You now use len()
successfully.
Upvotes: 0
Reputation: 19322
The idea behind a magic method is to be able to call it as x.__len__()
or len(x)
. They don't return the output until explicitly called or have or stored in class variables.
You can simply call the function explicitly as -
class foo(object):
def __init__(self,data):
self.data = data
def __len__(self):
print('i am in a magic function')
return len(self.data)
x = foo([1,2,3,4])
len(x) #or x.__len__() which is equivalent
i am in a magic function
4
Or if you want to trigger it during initialization, just add it in the __init__()
. Remember, init wouldn't return anything so you can push the output into stdio with a print.
class foo(object):
def __init__(self,data):
self.data = data
print(self.__len__())
def __len__(self):
print('i am in a magic function')
return len(self.data)
x = foo([1,2,3,4])
i am in a magic function
4
If you want to save it, then you can define a self.length
variable which can store it and can be retrieved by x.length
class foo(object):
def __init__(self,data):
self.data = data
self.length = self.__len__()
def __len__(self):
return len(self.data)
x = foo([1,2,3,4])
x.length
4
Upvotes: 2
Reputation: 1056
If we go with your class called foo()
we can call the method __len__
like this.
a = foo([1,2,3,4])
b = a.__len__()
Or if you want to save the length within the class:
class foo(object):
def __init__(self,data)
self.data = data
self.len = None
def __len__(self):
self.len = len(self.data)
a = foo([1,2,3,4])
a.__len__()
print(a.len)
Upvotes: -1
Reputation: 2343
Same way you call any other function. By its name.
print(x.__len__())
which will give 4 for your code
Upvotes: -1