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

Reply


Messages In This Thread
Special Methods in Class - by Nikhil - Mar-03-2021, 11:24 PM
RE: Special Methods in Class - by BashBedlam - Mar-04-2021, 03:23 AM
RE: Special Methods in Class - by Nikhil - Mar-04-2021, 06:25 PM
RE: Special Methods in Class - by buran - Mar-04-2021, 06:19 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Class test : good way to split methods into several files paul18fr 4 517 Jan-30-2024, 11:46 AM
Last Post: Pedroski55
  all of attributes and methods related to a special type akbarza 4 517 Jan-19-2024, 01:11 PM
Last Post: perfringo
  Structuring a large class: privite vs public methods 6hearts 3 1,106 May-05-2023, 10:06 AM
Last Post: Gribouillis
  access share attributed among several class methods drSlump 0 1,077 Nov-18-2021, 03:02 PM
Last Post: drSlump
  a function common to methods of a class Skaperen 7 2,670 Oct-04-2021, 07:07 PM
Last Post: Skaperen
  Listing All Methods Of Associated With A Class JoeDainton123 3 2,385 May-10-2021, 01:46 AM
Last Post: deanhystad
  too many methods in class - redesign idea? Phaze90 3 2,524 Mar-05-2021, 09:01 PM
Last Post: deanhystad
  Special Methods - what are they exactly? bytecrunch 1 1,694 Feb-07-2021, 01:38 AM
Last Post: Larz60+
  cant able to make methods interact with each other in the class jagasrik 2 1,827 Sep-16-2020, 06:52 PM
Last Post: deanhystad
  Question about naming variables in class methods sShadowSerpent 1 2,031 Mar-25-2020, 04:51 PM
Last Post: ndc85430

Forum Jump:

User Panel Messages

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