2017-08-14 92 views
0

我遇到了继承模型的一些问题。我想从给定的父对象创建一个新的子对象,我想访问这些属性。 这里是我的结构的简化模型。Python继承 - 父对象作为子对象的参数

class foo: 
def __init__(self,id,name): 
    self.id = id 
    self.name = name 

class bar(foo): 
    pass 

new = foo(id='1',name='Rishabh') 

x = bar(new) 

print(x.name) 

我想新对象的所有属性都要在x对象中继承。 谢谢

+1

你试过导入副本,然后x = copy.copy(新) – barny

+0

HI班尼谢谢你的回复。我刚刚在您的建议后尝试复制。但我仍然想知道是否有任何允许继承该对象作为参数的功能。 – reevkandari

+0

你所描述的“继承”不是面向对象意义上的继承,事实上它更像复制。 – barny

回答

0

起初,因为PEP8 Style Guide说,“类名通常应使用CapWords约定”。所以你应该重新命名你的课程为FooBar

你的任务可以通过使用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模块,不要做这个矫枉过正。

+0

我想我会去复制那么 – reevkandari