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
?
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.