最初に、PEP8 Style Guideと言うと、"クラス名は通常CapWordsの規約を使用するべきです。"クラスの名前をFoo
とBar
に変更する必要があります。
あなたの仕事は
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
モジュールを使用し、この過剰な操作はしないでください。
コピーをインポートしようとしましたが、x = copy.copy(new) – barny
HI Banny返信ありがとうございます。私はちょうどあなたの提案の後にコピーを試みました。オブジェクトとしてパラメータを継承できる機能があれば、私はまだ疑問を抱いていました。 – reevkandari
"継承する"と記述しているのは、オブジェクト指向の意味での継承ではなく、実際はコピーよりもはるかに似ています。 – barny