Click here to Skip to main content
15,892,737 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am a begineer with Python and I was wondering why cant we use the dunder method outside a class ? or maybe I am doing it wrong and not aware of any method.

What I have tried:

Google and other online resources
Posted
Updated 24-Sep-20 3:59am

You may use them outside (if I got you):
Python
class Foo:
  
    def __str__(self):
      return "a foo"

f = Foo()
print( f.__str__())
 
Share this answer
 
See The Python Tutorial — Python 3.7.9 documentation[^].

This works fine:
Python
def __foobar__():
    print("foobar")

__foobar__()
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900