Issue
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])
Solution
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.
Method 1: Call function explicitly
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
Method 2: Display during initialization
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
Method 3: Store and access as a class variable
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
Answered By - Akshay Sehgal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.