Python 空的初始化列表
我试图在init中获取一个空列表 因此,我期望从上面的代码中得到:len(c)=0 TypeError:类型为“rand”的对象没有len()Python 空的初始化列表,python,list,class,init,Python,List,Class,Init,我试图在init中获取一个空列表 因此,我期望从上面的代码中得到:len(c)=0 TypeError:类型为“rand”的对象没有len() 但我不断地得到上面的错误。我如何得到上面的结果 全局变量c及其同名属性是两个不同的对象。您需要的是len(c.c),而不是len(c)全局变量c及其同名属性是两个不同的对象。您想要len(c.c),而不是len(c)您可以使用内置的\u len\u方法: class rand: def __init__(self): self.
但我不断地得到上面的错误。我如何得到上面的结果 全局变量
c
及其同名属性是两个不同的对象。您需要的是len(c.c)
,而不是len(c)
全局变量c
及其同名属性是两个不同的对象。您想要len(c.c)
,而不是len(c)
您可以使用内置的\u len\u
方法:
class rand:
def __init__(self):
self.c = []
c = rand()
len(c)
输出:
class rand:
def __init__(self):
self.c = []
def __len__(self):
return len(self.c)
c = rand()
print(len(c))
您可以使用内置的
方法:
class rand:
def __init__(self):
self.c = []
c = rand()
len(c)
输出:
class rand:
def __init__(self):
self.c = []
def __len__(self):
return len(self.c)
c = rand()
print(len(c))
@新的,那不在你的问题中。你需要更清楚地知道你想要什么。听起来你想让rand
成为list
的一个子类。我想出来了。谢谢你的帮助:)@J.New很乐意帮忙@新的,那不在你的问题中。你需要更清楚地知道你想要什么。听起来你想让rand
成为list
的一个子类。我想出来了。谢谢你的帮助:)@J.New很乐意帮忙!