Tech C**P
15 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
Did you know that you can apply len python function on your classes? Let's say you have a Lessons class and when a use use len() function on your class it should return number of lessons inside of your class. For our sample let's say we have the below class:
class Lessons(object):
def __init__(self, lessons=0):
self.lessons = lessons

def insert(self, data):
# let's assume we have save data in database
self.lessons += 1

def __len__(self):
return self.lessons

This is a simple class that sets a fake lesson in your class and insert a new lesson.
std_lessons = Lessons(1)
print len(std_lessons) # output: 1

std_lessons.insert({})
print len(std_lessons) # output: 2

As you can see above we have used len on our class itself. In case you don't implemet __len__ on your class and use len() on it, there will be an AttributeError:
len(std_no_len)
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: Lessons instance has no attribute '__len__'

__len__ is built-in class and can be implemented in different scenarios. There are tons of built-in functions that you can master and use to improve code quality and prove that you are professional.

#python #class #builtin #len #__len__