神奇的方法__len__()
Magical method __len__()
如何使用class的对象调用__len__()
函数?
class foo(object):
def __init__(self,data)
self.data = data
def __len__(self):
return len(self.data)
x = foo([1,2,3,4])
你可以这样做:
>>>x = foo([1,2,3,4])
>>>len(x)
4
与调用任何其他函数的方式相同。按照它的名字。
print(x.__len__())
这将为您的代码提供 4
魔术方法背后的想法是能够将其称为 x.__len__()
或 len(x)
。在显式调用或存储在 class 变量中之前,它们不会 return 输出。
方法一:显式调用函数
您可以简单地显式调用该函数 -
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
方法二:初始化时显示
或者如果你想在初始化时触发它,只需在__init__()
中添加它。请记住,init 不会 return 任何东西,因此您可以使用 print.
将输出推送到 stdio
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
方法 3:作为 class 变量存储和访问
如果你想保存它,那么你可以定义一个self.length
变量来存储它并且可以通过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
如果我们使用您的 class 调用 foo()
,我们可以像这样调用方法 __len__
。
a = foo([1,2,3,4])
b = a.__len__()
或者如果你想在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)
如何使用class的对象调用__len__()
函数?
class foo(object):
def __init__(self,data)
self.data = data
def __len__(self):
return len(self.data)
x = foo([1,2,3,4])
你可以这样做:
>>>x = foo([1,2,3,4])
>>>len(x)
4
与调用任何其他函数的方式相同。按照它的名字。
print(x.__len__())
这将为您的代码提供 4
魔术方法背后的想法是能够将其称为 x.__len__()
或 len(x)
。在显式调用或存储在 class 变量中之前,它们不会 return 输出。
方法一:显式调用函数
您可以简单地显式调用该函数 -
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
方法二:初始化时显示
或者如果你想在初始化时触发它,只需在__init__()
中添加它。请记住,init 不会 return 任何东西,因此您可以使用 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
方法 3:作为 class 变量存储和访问
如果你想保存它,那么你可以定义一个self.length
变量来存储它并且可以通过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
如果我们使用您的 class 调用 foo()
,我们可以像这样调用方法 __len__
。
a = foo([1,2,3,4])
b = a.__len__()
或者如果你想在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)