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
Question : How would I create a
Circle
with the the basicFigure
properties of aRectangle
? """
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.