+ 2
Is it possible to inherit from a class in __init__ instead of: class Child(Parent):
The problem is that I want to pass a value to the constructor and based on the type of value I want to inherit from the type class of that value. Let's say I pass a str type object then my class should inherit from str. Is there a way?
12 Antworten
+ 4
Okay, I think I've found a way. check it out below.
Doesn't work with bool though because bool doesn't seem to allow inheritance.
https://code.sololearn.com/cBjVQ8P3Lr7f/?ref=app
+ 3
https://code.sololearn.com/c64BzvL68mD7/?ref=app
Here is the code
+ 3
I would set up eq, repr and str like this:
def __eq__(self, other):
return (
isinstance(other, Restrictive)
and type(self.val) == type(other.val)
and self.val == other.val
)
def __repr__(self):
return f"Restrictive({repr(self.val)})"
def __str__(self):
return str(repr(self.val))
If I try this...
a, b, c, d, e = (
Restrictive(i) for i in (5, 1, 1, True, '5')
)
s = {a, b, c, d, e}
print(s)
... it seems to already work.
I'm still unsure what you mean with the inheriting. I see nothing of that in your code example or task specification.
I mean, you're not inheriting, you're storing a value of a different type in an instance.
+ 2
Can you maybe describe your intended use case? (It sounds like there might be an easier way.)
+ 2
HonFu
Well basically I am trying to create a container for data types that overrides both __hash__ and __eq__
All it does is that it compares types restrictively, more like the === in JS. And of course, it is usable as a key in dictionaries and can be used inside a set.
Anything else behaves as usual
so, False != 0
But both of them behave like a regular bool and int objects.
+ 2
Hmmmmmmmm. 🤔
+ 1
HonFu I want it to work with its own type as well as built in types, so that I can say:
Restrictive(False) == 0 # False
Restrictive (True) == True # True
Restrictive (1) == Restrictive(1) # True
The code already works, the problem is that I want it to support any other built-in type method
So if self.val = 'Hello'
I want self to support string concatenation and behaves like a regular string.
Inheriting can only be done after the value is known.
+ 1
So you want to be able to write something like this?
a = Restrictive(5)
b = Restrictive('hi')
print(a*b)
# output: hihihihihi
+ 1
I searched for a method, but found nothing.
How does Child(Parent), way works? Is it a class method? If so, can't we just do it manually? However, it doesn't seem to be like that...
+ 1
HonFu Thanks a lot!!!
0
HonFu Yes!