如何在父类中创建子类的对象? [英] How can I create an object of a child class inside parent class?

查看:49
本文介绍了如何在父类中创建子类的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在test.py中有以下代码:

I have this code in test.py:

class Parent(object):
    def __init__(self):
        self.myprop1 = "some"
        self.myprop2 = "thing"

    def duplicate(self):
        copy = Parent()
        copy.myprop1 = self.myprop1
        copy.myprop2 = self.myprop2
        return copy

还有另一个在test2.py中:

And this other in test2.py:

from test import Parent

class Child(Parent):
    def __str__(self):
        return "{}, {}".format(self.myprop1, self.myprop2)

obj1 = Child()
obj2 = obj1.duplicate()
obj2.myprop1 = "another"
obj2.myprop2 = "stuff"

# Accessing properties
print("obj1, ", obj1.myprop1, ", ", obj1.myprop2)
print("obj2, ", obj2.myprop1, ", ", obj2.myprop2)
# Using Child method
print("obj1,", str(obj1))
print("obj2,", str(obj2))

运行test2.py,输出为:

Running test2.py, the output is:

obj1, some, thing
obj2, another, stuff
obj1, some, thing
obj2, <test.Parent object at 0x7fc1558e46d8>

我想知道是否可以在Parent内部创建Child的实例,但是由于可能会有更多孩子,我想知道 self 的类并创建该类的实例,然后复制属性,然后返回对象副本.

I wonder if I can create an instance of Child inside Parent, but because there could be more child, I want to know the class of self and create an instance of that one class, copy the attributes and then return the object copy.

此代码的目标是输出以下内容:

The goal for this code is to output this:

obj1, some, thing
obj2, another, stuff
obj1, some, thing
obj2, another, stuff

这意味着obj2是子对象,而不是父对象.

This means that obj2 is a Child object instead of a Parent object.

希望这很清楚,谢谢!

编辑:我不想使用 copy.copy() copy.deepcopy().如果您只想获取一份副本并实施一个更简单的解决方案,请检查

EDIT: I don't want to use copy.copy() or copy.deepcopy(). If you want to get only a copy and implement a simpler solution, check Moberg comment to see another related question that uses those functions. But, this question is intended to get another way of doing that and also know how to get the Class from an object and get another instance of that same Class. This particular case, is showing a relationship of parent-child between classes, that I added to show the whole context of my doubt.

推荐答案

只需不对类进行硬编码,请使用 type 检索实例的类,例如:

Just don't hard-code the class, use type to retrieve the class of the instance, something like:

class Parent(object):
    def __init__(self):
        self.myprop1 = "some"
        self.myprop2 = "thing"

    def duplicate(self):
        cls = type(self)
        copy = cls()
        copy.myprop1 = self.myprop1
        copy.myprop2 = self.myprop2
        return copy

这篇关于如何在父类中创建子类的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆