直接从父对象实例化子对象
我有两个从另一个对象继承,它们之间的唯一区别是一些属性字段:
class Parent:
def __init__(self,a, b):
self.a = a
self.b = b
def methodA(self):
# do something
pass
class Child(Parent):
def __init__(self,c,**kwargs):
self.c = c
super().__init__(**kwargs)
我有一个父对象的实例,我想在python中找到一种快速的方法来创建一个只有一个只有具有的子对象的实例使用已经存在的父对象的另一个字段。
是否有Python或模块可以让您轻松地做到这一点。在我的真实代码中,父类有数百个字段,仅重新分配其值有点低效。
I have two objects one inherits from the other and the only difference between them is a few attribute fields:
class Parent:
def __init__(self,a, b):
self.a = a
self.b = b
def methodA(self):
# do something
pass
class Child(Parent):
def __init__(self,c,**kwargs):
self.c = c
super().__init__(**kwargs)
I have an instance of the parent object and I want to find a fast way in python to create an instance of the child object which only has one additional field by using the already existing parent object.
Is there a python way or module that lets you do that easily. IN my real code the parent class has hundreds of fields and it is a bit inefficient to just reassign its value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
规范的解决方案是将类方法添加到
Child
作为构造函数的。它采用parent
实例,然后返回带有适当属性的child
实例。例如:
我认为您的
parent
具有数百个属性的类与答案无关。是的,必须在from_parent
方法中明确地写出parent> parent
实例的每个属性是很乏味的,但这只是一个限制,无论如何还是要有一个具有许多属性的类。可能的是,更好的设计选择是将parent>属性>属性的组封装到适当的类中,以便在初始化后只需要将这些实例交付到
child
类。The canonical solution is to add a class method to
Child
that works as a constructor. It takes aParent
instance and returns theChild
instance with the proper attributes.For example:
I would argue that your
Parent
class having hundreds of attributes is irrelevant to the answer. Yes, it's tedious having to explicitly write every attribute of theParent
instance in thefrom_parent
method, but that's simply a limitation of having a class with that many attributes anyway. Possibly, a better design choice would be to encapsulate groups ofParent
attributes into proper classes, so that only those instances need to be delivered to theChild
class upon initialization.好的,制作一种使用父属性并创建子对象的方法的其他建议是可以的,但我认为添加了不必要的代码。我做了这个解决方案,最终使用了。它不直接接受父对象作为参数,但我认为这更简洁:
Ok the other suggestions for making a method that takes in parent attributes and creates a child object is ok but adds unnecessary code I think. I made this solution, which I ended up using. It doesnt accept the parent object directly in as an argument but it is more concise I think: