Creating equivalent classes in Python?

I played with overloading or masking classes in Python. Do the following code examples to 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 the good answer from gs, it happened to me that I really wanted to ask: “Attributes” make these classes different?

Insofar as

>>> dir(a) == dir(b)
True

and

>>> print Sample
<class '__main__.Sample'>
>>> print CustASample
<class '__main__.Sample'>

but

>>> Sample == CustASample
False
+3
source share
2 answers

No, they are still different.

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

Here is 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 do this in a method __new__instead of __init__:

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

To answer your updated question:

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

Why not be equal to b, since both are just objects without attributes?

, . == __eq__, . , . a is b.

is . ( CPython - .) :

>>> id(a)
156808
+10

, . , id (Sample). , , . . , [] is [].

EDIT: , gs .

0

Source: https://habr.com/ru/post/1727231/


All Articles