起初,因为PEP8 Style Guide说,“类名通常应使用CapWords约定”。所以你应该重新命名你的课程为Foo
和Bar
。
你的任务可以通过使用object.__dict__
和你的子类(Bar
)
class Foo:
def __init__(self, id, name):
self.id = id
self.name = name
class Bar(Foo):
def __init__(self, *args, **kwargs):
# Here we override the constructor method
# and pass all the arguments to the parent __init__()
super().__init__(*args, **kwargs)
new = Foo(id='1',name='Rishabh')
x = Bar(**new.__dict__)
# new.__dict__() returns a dictionary
# with the Foo's object instance properties:
# {'id': '1', 'name': 'Rishabh'}
# Then you pass this dictionary as
# **new.__dict__
# in order to resolve this dictionary into keyword arguments
# for the Bar __init__ method
print(x.name) # Rishabh
重写__init__
方法来完成但是,这不是一个做事的传统方式。如果你想有一个实例,这是另一个实例的副本,你应该使用copy
模块,不要做这个矫枉过正。
你试过导入副本,然后x = copy.copy(新) – barny
HI班尼谢谢你的回复。我刚刚在您的建议后尝试复制。但我仍然想知道是否有任何允许继承该对象作为参数的功能。 – reevkandari
你所描述的“继承”不是面向对象意义上的继承,事实上它更像复制。 – barny