A
にはold_name()
メソッドの基本クラスがありました。最初A.old_name()
を呼び出すことにより、A
から継承し、old_name()
を上書きするために使用サブクラス:Python:下位互換性を維持しながらメソッドの名前を変更
class A():
'''Old A class'''
def old_name(self):
print('foo')
class B(A):
'''Old Subclass.'''
def old_name(self):
A.old_name(self)
print('bar')
b = B()
b.old_name() # must print 'foo bar', prints 'foo bar'
今は、私がnew_name
へold_name
を変更したいです。しかし、私はAPIを壊すことはしたくないので、B
のような古いサブクラスのは、new_name()
とold_name()
の両方の呼び出しをサポートします。また、両方のメソッドをサポートする新しいサブクラス(C
など)も必要です。これによって、new_name()
が呼び出されたか、old_name()
が呼び出されたかを問わず、foo bar
を印刷する必要があります。私はクラスB
を変更することができません:変更できる唯一のクラスはクラスA
です。
これは私が思いついたものです。残念ながらB
はへの直接呼び出しをサポートしていないため、b.old_name()
をバイパスします。
class A():
'''New A class. Now A has to support new_name AND old_name.'''
def old_name(self):
self.new_name()
def new_name(self):
print('foo')
class B(A):
'''Old Subclass, still using old_name'''
def old_name(self):
A.old_name(self)
print('bar')
class C(A):
'''New Subclass, now using new_name'''
def new_name(self):
A.new_name(self)
print('bar')
b = B()
b.new_name() # must print 'foo bar', only prints 'foo'. Bad.
b.old_name() # must print 'foo bar', prints 'foo bar'. OK.
c = C()
c.new_name() # must print 'foo bar', prints 'foo bar'. OK.
c.old_name() # must print 'foo bar', prints 'foo bar'. OK.
どのようなヘルプが大幅にappriciatedでしょう!
'B'のようなクラスBであなたの
new_name
とold_name
を上書きする必要があります'new_name'を実装します。また 'warnings'を使って' old_name'が非難されたことを示すべきです。 – jonrsharpeクラス「B」を変更できないことを明確にするために質問を編集しました。私は間違いなく、この問題がソートされているときに警告を使用します、ありがとう。 – Niourf
次に、new_nameがold_nameを指しているようにコールを取り消さない限り、修正することはできません – jonrsharpe