1

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
Bastian
  • 901
  • 7
  • 23
  • 2
    Are you sure you want to do this in the constructor? I would find this very confusing as a user of your class. Why dont you just make a free function that returns the correct object? – pschill Dec 03 '18 at 11:55
  • 2
    Not recommended at all. – 0xInfection Dec 03 '18 at 12:04

1 Answers1

1

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?

Valentino
  • 7,291
  • 6
  • 18
  • 34