0

In the below list of attributes,

>>> dir(object)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

__eq__, __ne__ & __hash__ are not shown as attributes. They are attributes of meta class type

>>> dir(type)
    [... '__eq__', .... '__hash__', ... '__ne__', ...]
>>>

and object is not in is-a relation with type

>>> issubclass(object, type)
    False
>>> issubclass(type, object)
    True

But, I see these attributes part of object,

>>> object.__eq__
    <method-wrapper '__eq__' of type object at 0x905b80>
>>> object.__ne__
    <method-wrapper '__ne__' of type object at 0x905b80>
>>> object.__hash__
    <slot wrapper '__hash__' of 'object' objects>
>>> 

This allows,

class X(object):
   pass

class X to override these attributes.


Question:

Are these attributes of object?

overexchange
  • 15,768
  • 30
  • 152
  • 347

2 Answers2

2

The methods in type define how a class behaves, the methods in object implement how instances behave.

Using your subclass of object:

class X(object):
    pass

Then

X == X

will call type.__eq__(X, X)

But:

X() == X()

will call object.__eq__(X, X)

At least as long you don't override these magic methods (either in your X directly or when you define your own metaclass for X).


If you "go meta", then it's important to know that metaclasses are to classes what instances are to classes:

>>> isinstance(object, type)   # class & metaclass
True

>>> isinstance(X(), X)         # instance & class
True
MSeifert
  • 145,886
  • 38
  • 333
  • 352
1

They are part of the data model customization, called 'magic methods', you have to think of them as an interface for interaction with python functionalities. Here is all the documentation relating this.

Netwave
  • 40,134
  • 6
  • 50
  • 93