开发者

Creating equivalent classes in Python?

I played around with overloading or masking classes i开发者_StackOverflow社区n 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.

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


Classes also, not only instances, are objects. For example, you can get id(Sample). Try it and see that these two numbers differ, as differ the classes' memory locations. They are not the same object. It's like asking whether [] is [].

EDIT: Too late and the explanation by gs is better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜