Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating equivalent classes in Python?

Tags:

python

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
like image 277
Bertolt Avatar asked Sep 11 '26 04:09

Bertolt


1 Answers

No, they are still different.

a = CustASample()
b = Sample()
a.__class__ is b.__class__
-> False

Here's how you could do it:

class A(object):
    def __init__(self):
        self.__class__ = B

class B(object):
    def bark(self):
       print "Wuff!"

a = A()
b = B()
a.__class__ is b.__class__
-> True

a.bark()
-> Wuff!

b.bark()
-> Wuff!

Usually you would do it in the __new__ method instead of in __init__:

class C(object):
    def __new__(cls):
        return A()

To answer your updated question:

>>> a = object()
>>> b = object()
>>> a == b
False

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 it a is b gets used.

is compares the ids of the objects. (In CPython the memory address.) You can get the id of an object like this:

>>> id(a)
156808
like image 68
Georg Schölly Avatar answered Sep 12 '26 17:09

Georg Schölly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!