Python继承:从子类创建父类对象

时间:2019-09-04 10:41:03

标签: python inheritance

我有一组班级,其中孩子来自父母。 我试图实现的是创建一个父类的对象,该对象从子类的对象获取所有值。 我发现的唯一方法是:

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))

输出确实是

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

但是我不确定这是否是一种好方法,pythonesque和无风险的方法

1 个答案:

答案 0 :(得分:0)

  

问题:如何使用Circle的基本Figure属性创建Rectangle?   “”“

您可以通过在基础new_from中实现方法class Figure来做到这一点。
例如:

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__))
  

输出

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

使用Python测试:3.6