Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

python - How to replace an instance in __init__() with a different object?

I am calling a constructor in ClassA and want to have the resulting object be of a different class (ClassB) if a certain condition is met. I've tried replacing the first argument to __init__() ('self' in the example below) within __init__() but it doesn't seem to do what I want.

in main:

import ClassA

my_obj = ClassA.ClassA(500)
# unfortunately, my_obj is a ClassA, but I want a ClassB!

in ClassA/__init__.py:

import ClassB

class ClassA:
    def __init__(self,theirnumber):
        if(theirnumber > 10):
            # all big numbers should be ClassB objects:
            self = ClassB.ClassB(theirnumber)
            return
        else:
            # numbers under 10 are ok in ClassA.
            return

in ClassB/__init__.py:

class ClassB:
    pass
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need __new__() for that. (And you also need to make it a new-style class, assuming you're using Python 2, by subclassing object.)

class ClassA(object):
    def __new__(cls,theirnumber):
        if theirnumber > 10:
            # all big numbers should be ClassB objects:
            return ClassB.ClassB(theirnumber)
        else:
            # numbers under 10 are ok in ClassA.
            return super(ClassA, cls).__new__(cls, theirnumber)

__new__() runs as part of the class instantiation process before __init__(). Basically __new__() is what actually creates the new instance, and __init__() is then called to initialize its properties. That's why you can use __new__() but not __init__() to alter the type of object created: once __init__() starts, the object has already been created and it's too late to change its type. (Well... not really, but that gets into very arcane Python black magic.) See the documentation.

In this case, though, I'd say a factory function is more appropriate, something like

def thingy(theirnumber):
    if theirnumber > 10:
        return ClassB.ClassB(theirnumber)
    else:
        return ClassA.ClassA(theirnumber)

By the way, note that if you do what I did with __new__() above, if a ClassB is returned, the __init__() method you wrote in ClassA will not be called on the ClassB instance! When you construct the ClassB instance inside ClassA.__new__(), its own __init__() method (ClassB.__init__()) will be run at that point, so hopefully it makes sense that Python shouldn't run another unrelated __init__() method on the same object. But this can get kind of confusing, which is probably another argument in favor of the factory function approach.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...