Reputation: 119
If I remember correctly, in C++ it is possible to call a parent's class's constructor on a subclass's instance, so that an instance of the parent class will be created so that only the overlapping attributes will be copied over. Does such a functionality exist in python such that the following 'python' code would do the same?
If I have a parent class Fruit
class Fruit():
def __init__(self, color):
self.color = color
and a child class Apple
class Apple(Fruit):
def __init__(self, color, seeds):
self.seeds = seeds
super().__init__(color)
You could do
an_apple = Apple('red', 42)
a_fruit = Fruit(an_apple)
and get a red fruit.
Upvotes: 0
Views: 38
Reputation: 39364
The only think I can think of is to make a Factory Method:
class Fruit():
def __init__(self, color):
self.color = color
@staticmethod
def MakeFruit(aFruit):
return Fruit(aFruit.color)
usage:
an_apple = Apple('red', 42) #assuming Apple as before
a_fruit = Fruit('blue')
a_red_fruit = Fruit.MakeFruit(an_apple)
Upvotes: 1