Reputation: 938
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
Upvotes: 1
Views: 443
Reputation: 7361
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?
Upvotes: 1