2017-08-14 93 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