简体   繁体   中英

Make __init__ create other class in python

I created my own class my_class being initiated with two variables, a and b .

In case one attempts to create an object of my_class with a==b , I would like that object to simply be of type(a) and not my_class .

How can this be implemented? How would the following implementation need to be modified?

class myclass:
    def __init__(self, a, b):
        if a == b:
            self = a
        else:
            myclass.a = a
            myclass.b = b

As other people say in the comment, I also think is not recommended. But if you really need to do it this way, this code should do it:

class myclass(object):
    def __new__(cls, a, b):
        if a == b:
            return a
        else:
            instance = super(myclass, cls).__new__(cls)
            return instance

    def __init__(self, a, b):
        self.a = a
        self.b = b

You can test it:

x = myclass(4, 4)
y = myclass(4, 6)
print(x) #this prints 4
print(y) #this prints <__main__.myclass object at ...>
print(y.a, y.b) #this prints 4 6

The fact is that __init__ cannot return anything, if you want to return something else you shoud use __new__

See also: How to return a value from __init__ in Python?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM