Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 空的初始化列表_Python_List_Class_Init - Fatal编程技术网

Python 空的初始化列表

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.

我试图在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 = []

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很乐意帮忙!