-1

When we print operator.eq.__name__ we get the output 'eq'. This implies that operator.eq is a class. But we can use it as a function as well. operator.eq("test", "test") returns True. How is operator.eq implemented? Is it a class or a function?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Koushik Sahu
  • 99
  • 1
  • 1
  • 9
  • Not an exact duplicate but FWIW I do explain how a `.eq` comparison works under the hood in python. – cs95 Jun 11 '20 at 08:19

1 Answers1

-1

operator.eq is a function of the operator module. All functions have a __name__ attribute, as do most classes.

eq is pretty simple, take a look at the source:

def eq(a, b):
    "Same as a == b."
    return a == b

You can demonstrate this in CLI with the following code.

def cool_name():
    pass

class NeatName:
    pass

print(cool_name.__name__)
print(NeatName.__name__)

Interestingly, a function is still a class, and can be treated like one. You can assign properties and functions to another function.

cool_name.foo = "foo"
print(cool_name.foo)

def bar_func():
    print("bar")

cool_name.bar = bar_func

cool_name.bar()
Sam Morgan
  • 2,445
  • 1
  • 16
  • 25
  • "All functions have a `__name__` attribute, as does nearly every object in Python" - on the contrary, most objects do not have a `__name__`. It's mostly just functions and classes that have a `__name__`. – user2357112 Jun 11 '20 at 07:56
  • "Interestingly, a function is still a class, just like everything in Python" - this is also wrong. Functions are not classes. Most things in Python are not classes. – user2357112 Jun 11 '20 at 08:02
  • Since the base `object` implements `__name__`, wouldn't that, by default, mean most Python objects have `__name__`? The only ones I can think of that don't are the built-in types. – Sam Morgan Jun 11 '20 at 08:03
  • No. Contrary to common misconception, objects do not automatically have all attributes of their class. Default attribute lookup behavior includes a search through the `__dict__`s of an object's class and all superclasses, but that search won't find class attributes that are resolved through the *metaclass*. – user2357112 Jun 11 '20 at 08:08
  • Sorry I am new to python. I am coming to python from c++ and the concept of function having attributes is new to me. How can function have attributes? Can you redirect me to any useful link where I can find more details? – Koushik Sahu Jun 11 '20 at 09:03