I played around with overloading or masking classes in Python. Do the following code examples create equivalent classes?
class CustASample(object):
def __init__(self):
self.__class__.__name__ = "Sample"
def doSomething(self):
dummy = 1
and
class Sample(object):
def doSomething(self):
dummy = 1
EDIT: From the comments and and the good answer by gs, it occured to me, that I really wanted to ask: What “attributes” make these classes differ?
Because
>>> dir(a) == dir(b)
True
and
>>> print Sample
<class '__main__.Sample'>
>>> print CustASample
<class '__main__.Sample'>
but
>>> Sample == CustASample
False
No, they are still different.
Here’s how you could do it:
Usually you would do it in the
__new__method instead of in__init__:To answer your updated question:
Why would a not be equal to b, since both are just plain objects without attributes?
Well, that answer is simple. The == operator invokes
__eq__, if it’s available. But unless you define it yourself it’s not. Instead of ita is bgets used.iscompares the ids of the objects. (In CPython the memory address.) You can get the id of an object like this: