Reputation: 980
I want to provide method to a class, so that it gets transformed into a special case, represented by a subclass. I'm not sure, however what is the best way to do it.
Here is an illustrative example:
class Vector(pd.Series):
def normalize(self) -> "NormalizedVector":
result: "NormalizedVector" = self / sum(self) # type:ignore
return result
class NormalizedVector(Vector):
pass
There are issues with this implementation, though:
isinstance(vector.normalize(), NormalizedVector)
will be False
# type: ignore
annotation is required for static type checkingSo my question is: what is a clean way of achieving this?
The alternative I found was using dynamic allocation:
class Vector(pd.Series):
pass
class NormalizedVector(Vector):
pass
def normalize_vector(self: Vector) -> NormalizedVector:
return NormalizedVector(self / sum(self))
Vector.normalize = normalize_vector
However:
__name__
Upvotes: 0
Views: 42
Reputation: 531165
A type hint alone doesn't cause a value to become the hinted type. You need to create an instance. Your second approach works because you actually created that instance. The explicit assignment is unnecessary.
class Vector(pd.Series):
def normalize(self) -> "NormalizedVector":
return NormalizedVector(self / sum(self))
class NormalizedVector(Vector):
pass
Upvotes: 3