-1

1- In Python, which classes do the methods that begin and end with two underscores (eg: __gt__, __eq__, ...) belong to?

2- Which classes/modules are imported implicitly for all Python programs?

3- Is there a general way to get the class name for any given method?

onur surme
  • 132
  • 8
  • 1
    1. Whichever classes define them – zondo Apr 23 '16 at 15:06
  • Take a look at [A Guide to Python's Magic Methods](http://www.rafekettler.com/magicmethods.html). FWIW, these methods are sometimes known as [dunder methods](http://nedbatchelder.com/blog/200605/dunder.html). – PM 2Ring Apr 23 '16 at 15:42
  • 2. The `__builtins__` is module is always present. – PM 2Ring Apr 23 '16 at 15:49
  • Use bacticks (\`) to format code so that you don't have to write _ _ gt _ _. For example: \`__gt__\` comes out as `__gt__` – Alex Hall Apr 23 '16 at 17:19
  • Possible duplicate of [Special (magic) methods in Python](http://stackoverflow.com/questions/1090620/special-magic-methods-in-python) – Bharel Apr 23 '16 at 20:27

1 Answers1

1

you can use dir() to find out

for k in dir(__builtins__):
    print str(k) + " : :\n" + str(dir(eval(k))) + "\n\n"
    try:
        a = input("type enter for next:")
    except(SyntaxError):
        continue

you can use ctrl+c to end the programs excecuteion and of course jsut call dir() on any particular type you are interested in.

kpie
  • 9,588
  • 5
  • 28
  • 50
  • print(int.__gt__(2,10)) -> False print(int.__gt(20,10)) -> True . Using your answer, I've found the __gt__ method we use like 2>10. Thanks. Indeed, many classes use their own implementations of methods like __add__, __gt__, etc. But for numbers, I could guess that the right class is "int" . – onur surme Apr 23 '16 at 20:51
  • @onur how this comment is even remotely related to the answer by kpie? – lejlot Apr 23 '16 at 20:52
  • What version of python are you using? – kpie Apr 23 '16 at 20:57
  • 1
    Using this answer, I could see a list of classes and their methods. And among those methods, I could find `__gt__` method belongs to "int". I've tried to use `int.__gt__` and it worked correctly, and by my comment above, I wanted to show this. As I'm using Pyhton 3, I've modifed the print statement. – onur surme Apr 23 '16 at 21:01
  • Glad I could help. – kpie Apr 23 '16 at 21:09