Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Special Methods in Class
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 ()))
Nikhil likes this post
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:

class Eggs:
    def __str__(self):
        return 'instance of my class Eggs'

spam = Spam() # instance of class Spam
eggs = Eggs() # instance of class Eggs

<__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__
Nikhil likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

It Helpful really thanks :-)

Possibly Related Threads…
Thread Author Replies Views Last Post
  access share attributed among several class methods drSlump 0 259 Nov-18-2021, 03:02 PM
Last Post: drSlump
  a function common to methods of a class Skaperen 7 714 Oct-04-2021, 07:07 PM
Last Post: Skaperen
  Listing All Methods Of Associated With A Class JoeDainton123 3 1,051 May-10-2021, 01:46 AM
Last Post: deanhystad
  too many methods in class - redesign idea? Phaze90 3 1,204 Mar-05-2021, 09:01 PM
Last Post: deanhystad
  Special Methods - what are they exactly? bytecrunch 1 735 Feb-07-2021, 01:38 AM
Last Post: Larz60+
  cant able to make methods interact with each other in the class jagasrik 2 797 Sep-16-2020, 06:52 PM
Last Post: deanhystad
  Question about naming variables in class methods sShadowSerpent 1 967 Mar-25-2020, 04:51 PM
Last Post: ndc85430
  a class calling one of its own methods? Skaperen 1 939 Jul-21-2019, 04:43 AM
Last Post: Gribouillis
  Do objects get their own copy of the class methods? Charles1 1 1,221 Feb-02-2019, 04:40 PM
Last Post: ichabod801
  Attibute Error: Two methods in a class, one I can reach, the other not (phantom file? GaryKuipers 4 1,884 Aug-28-2018, 02:32 PM
Last Post: GaryKuipers

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020