I am trying to subclass from a parent class in library code and am having some challenges. Here's an example to illustrate what I mean. The parent class (Parent
) has an alternate constructor (Parent.from_list_of_strings
). Unfortunately the alternate constructor does not refer to its own cls
attribute. Rather it calls an outer function (from_list_of_strings
) to do its work:
# library code
def from_list_of_strings(list_of_strings):
new_list = []
for string in list_of_strings:
new_list.append(float(string))
return Parent(new_list)
class Parent():
def __init__(self, regular_list):
self.min_of_list = min(regular_list)
@classmethod
def from_list_of_strings(cls, list_of_strings):
return from_list_of_strings(list_of_strings)
# my code
class Child(Parent):
pass
if __name__=='__main__':
print()
p = Parent.from_list_of_strings(['2', '-2', '5', '8'])
print(type(p))
print(p.min_of_list)
print()
c = Child.from_list_of_strings(['2', '-2', '5', '8'])
print(type(c))
print(c.min_of_list)
The problem here is that even though I create an instance of Child
, making use of the inherited from_list_of_strings
method still returns an instance of the parent class. Here is the output generated from the script above:
<class '__main__.Parent'>
-2.0
<class '__main__.Parent'>
-2.0
If I cannot modify the library code, what is the best way of inheriting the ability to use the classmethod
and returning an instance of Child
such that I get the following output?
<class '__main__.Parent'>
-2.0
<class '__main__.Child'>
-2.0
For reference, in reality I am trying to subclass the GeoDataFrame
class from the geopandas
library. The from_file
classmethod is the problematic method. Here is the related issue on github..
Aucun commentaire:
Enregistrer un commentaire