2017-08-14 13 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(new) – barny

+0

HI Banny返信ありがとうございます。私はちょうどあなたの提案の後にコピーを試みました。オブジェクトとしてパラメータを継承できる機能があれば、私はまだ疑問を抱いていました。 – reevkandari

+0

"継承する"と記述しているのは、オブジェクト指向の意味での継承ではなく、実際はコピーよりもはるかに似ています。 – barny

答えて

0

最初に、PEP8 Style Guideと言うと、"クラス名は通常CapWordsの規約を使用するべきです。"クラスの名前をFooBarに変更する必要があります。

あなたの仕事は object.__dict__を使用し、あなたの子供のクラスで __init__メソッドをオーバーライドすることで行うことができます

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 

しかし、これは物事の従来の方法ではありません。別のインスタンスをコピーしたい場合は、おそらくcopyモジュールを使用し、この過剰な操作はしないでください。

+0

私はコピーのために行くと思います – reevkandari

関連する問題