Did you know that you can apply
This is a simple class that sets a fake lesson in your class and insert a new lesson.
As you can see above we have used
#python #class #builtin #len #__len__
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__
https://spyhce.com/blog/understanding-new-and-init
#python27 #python3 #__init__ #__new__ #old_style #new_style #OOP #class #super
#python27 #python3 #__init__ #__new__ #old_style #new_style #OOP #class #super
Spyhce
__new__ and __init__ | Spyhce blog
The __new__ and __init__ methods behave differently between themselves and between the old-style versus new-style python class definitions.