[英]How can I create an object of a child class inside parent class?
我在 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 中的另一个:
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,output为:
obj1, some, thing
obj2, another, stuff
obj1, some, thing
obj2, <test.Parent object at 0x7fc1558e46d8>
我想知道我是否可以在 Parent 中创建 Child 的实例,但是因为可能有更多的 child,所以我想知道self的 class 并创建一个 class 的实例,复制属性然后返回 ZA8CFDE6331BD59EB2AC666F8911C4B6 副本。
这段代码的目标是 output 这个:
obj1, some, thing
obj2, another, stuff
obj1, some, thing
obj2, another, stuff
这意味着 obj2 是 Child object 而不是 Parent object。
希望这很清楚,谢谢!
编辑:我不想使用copy.copy()
或copy.deepcopy()
。 如果您只想获得一份副本并实施更简单的解决方案,请查看Moberg 评论以查看使用这些功能的另一个相关问题。 但是,此问题旨在获得另一种方法,并且还知道如何从 object 获取 Class 并获取相同 Class 的另一个实例。 这个特殊情况显示了类之间的父子关系,我添加它以显示我怀疑的整个上下文。
只是不要对 class 进行硬编码,使用type
来检索实例的 class,例如:
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
是的,使用type(self)
获取 object 的类型。 还可以考虑使用 dunder 方法__copy__
实现复制以支持内置的copy()
。
def __copy__(self):
return type(self)()
class 方法可能更好,因为它可以让您控制正在创建的 object 的类型。
class Parent(object):
def __init__(self):
self.myprop1 = "some"
self.myprop2 = "thing"
@classmethod
def from_object(cls: 'T', obj: Parent) -> 'T':
copy = cls()
copy.myprop1 = obj.myprop1
copy.myprop2 = obj.myprop2
return copy
class Child(Parent):
def __str__(self):
return "{}, {}".format(self.myprop1, self.myprop2)
obj1 = Child()
obj2 = Child.from_object(obj1) # A new Child
obj3 = Parent.from_object(obj1) # A new Parent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.