清空__init__列表

时间:2017-12-07 02:10:16

标签: python list class init

class rand:

    def __init__(self):
        self.c = []

c = rand()

len(c)

我想在 init 中获取一个空列表。

所以,我对上述代码的期望是:len(c)= 0

TypeError:类型' rand'的对象没有len() 但我一直得到上​​面的错误。我如何得到上面的结果?

2 个答案:

答案 0 :(得分:4)

您可以使用内置__len__方法:

class rand:
   def __init__(self):
      self.c = []
   def __len__(self):
      return len(self.c)

c = rand()
print(len(c))

输出:

0

答案 1 :(得分:1)

全局变量c及其同名属性是两个不同的对象。您想要len(c.c),而不是len(c)