Home Empty __init__ list
Reply: 2

Empty __init__ list

J.New
1#
J.New Published in 2017-12-07 02:10:15Z
class rand:

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

c = rand()

len(c)

I am trying to get an empty list in init.

So, what I am expecting from the code above is this: len(c) = 0

TypeError: object of type 'rand' has no len() But I keep getting the error above. How do I get the result above?

chepner
2#
chepner Reply to 2017-12-07 02:12:49Z

The global variable c and its attribute of the same name are two different objects. You want len(c.c), not len(c).

Ajax1234
3#
Ajax1234 Reply to 2017-12-07 02:13:22Z

You can use the builtin __len__ method:

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

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

Output:

0
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.312024 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO