0

I have a set of classes where a child is derived from a parent. What I am trying to achieve is to create an object of the parent class that gets all its values from an object of the child class. The only way I found is this:

from copy import deepcopy
class Parent(object):
    def __init__(self, value):
        self.val = value

class Child(Parent):
    def __init__(self, val=8):
         super(Child, self).__init__(val)
         chval=5
par=Parent(3)
ch=Child()
parent= Parent(4)
parent.__dict__ = deepcopy(super(Child, ch).__dict__)
print(parent.val)
print(type(par), type(ch), type(parent))

The output is indeed

8
(<class '__main__.Parent'>, <class '__main__.Child'>, <class '__main__.Parent'>)

but I am not sure whether this is a good, pythonesque and risk-free method of doing this

7
  • 2
    The problem isn't with the approach, but with the OOP design that the child object inherits the parent class' attributes & methods and not the other way around. Commented Sep 4, 2019 at 10:44
  • I have never heard of creating a parent class from a child class and I guess it is not possible. Please correct me if I am wrong. Commented Sep 4, 2019 at 10:45
  • 3
    That is not how OOP is supposed (nor designed) to work. Commented Sep 4, 2019 at 10:47
  • 3
    The Child is-a Parent so the object you want to create is actually there - what is your use case (plus this chval does not do anything) Commented Sep 4, 2019 at 10:52
  • The use case is rather complicated; basically I have an object class that is a node in a tree which is derived from some single-object class and I want to create a new node that shares all values of the single-object class but not the nodes attributes. Commented Sep 4, 2019 at 10:56

1 Answer 1

1

Question: How would I create a Circle with the the basic Figure properties of a Rectangle? """

You can do this by implementing a method new_from in the Base class Figure.
For example:

class Figure:
    def __init__(self, p):
        self.properties = p

    @classmethod
    def new_from(cls, obj):
        if issubclass(obj.__class__, Figure):
            _new = cls(obj.properties)
            return _new
        else:
            raise TypeError('Expected subclass of <class Figure>, got {}.'\
                                .format(type(obj)))

    def __repr__(self):
      return "<class '{}' properties:{}"\
                .format(self.__class__.__name__, self.properties)

class Rectangle(Figure):
    pass    

class Circle(Figure):
    pass

r1 = Rectangle({'test': 'r1.property'})
r2 = Rectangle.new_from(r1)
c1 = Circle({'test': 'c1.property'})
c2 = Circle.new_from(r1)

for obj in [r1, r2, c1, c2]:
    print(obj)  # '{}\n{}'.format(obj, obj.__dict__))

Output:

<class 'Rectangle' properties:{'test': 'r1.property'}
<class 'Rectangle' properties:{'test': 'r1.property'}
<class 'Circle' properties:{'test': 'c1.property'}
<class 'Circle' properties:{'test': 'r1.property'}

Tested with Python: 3.6

Sign up to request clarification or add additional context in comments.

2 Comments

Late to the question, but what about when you can't add new methods to base class?
@MorJ "what about when you can't add new methods to base class": Means you want to extend Figure then do class MyFigure(Figure) and use this afterwards, e.g. Rectangle(MyFigure):

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.