Hello, I want to know how the special methods in class will be useful in Python like
__str__ and __len__
Can anyone clearly explain this method will be usefull and how?
__str__ is what prints when you print the class. __len__ is what is returned when you ask for the len () of the class. Run this and see.
class Tester :
def __str__ (self) :
return 'Hello world.'
def __len__ (self) :
return 13
print (Tester ())
print (len (Tester ()))
As described in
the docs:
Quote:A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators.
with respect to examples you give us:
class Spam:
pass
class Eggs:
def __str__(self):
return 'instance of my class Eggs'
spam = Spam() # instance of class Spam
eggs = Eggs() # instance of class Eggs
print(spam)
print(eggs)
Output:
<__main__.Spam object at 0x7fd8d323c978>
instance of my class Eggs
Do you see the difference? Note that with respect to printing, there is also related
__repr__()
methood. You can check
what is the difference between __str__ and __repr__
It Helpful really thanks :-)