Python Forum
Special Methods in Class - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Special Methods in Class (/thread-32759.html)



Special Methods in Class - Nikhil - Mar-03-2021

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?


RE: Special Methods in Class - BashBedlam - Mar-04-2021

__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 ()))



RE: Special Methods in Class - buran - Mar-04-2021

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__


RE: Special Methods in Class - Nikhil - Mar-04-2021

It Helpful really thanks :-)