简体   繁体   English

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

[英]Python inheritance: Create parent class object from child class

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 但我不确定这是否是一种很好的,Python风格且无风险的方法

Question : How would I create a Circle with the the basic Figure properties of a Rectangle ? 问题 :如何用Rectangle的基本Figure属性创建一个Circle """ “”

You can do this by implementing a method new_from in the Base class Figure . 您可以通过在基class Figure实现new_from方法来实现。
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 使用Python测试:3.6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python继承:在父类中创建子对象 - Python inheritance: create child object in parent class Python Inheritance - 将用户输入的值从父母传递给孩子 class - Python Inheritance - Carrying a user inputted value from parent to child class 从子类的ModelForm创建父类对象 - Create Parent Class object from child class's ModelForm Python类继承防止父类调用子类方法 - Python Class Inheritance Prevent Parent Class from Calling Child Class Method Python类:inheritance的区别和在子类里面创建父类class实例(类组成) - Python Classes: differences between inheritance and create a parent class instance inside the child (class composition) 在父类中创建子类对象 - Create child class object in parent class Python继承:修改对象的父类 - Python inheritance: modify a parent class of an object 如何在SQLAlchemy的连接表继承中从父类创建子类? - How do I create a child class from a parent class in SQLAlchemy's Joined Table Inheritance? Python AttributeError:来自父函数的类继承 - Python AttributeError: Class Inheritance From a Parent Function 在继承的情况下,是否可以通过在python中使用子类对象引用来调用第二个父类方法? 如果是,那怎么办? - Is it possible to call 2nd parent class method by using child class object reference inside python in case of inheritance? If yes then how?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM