オブジェクトの特別なメソッドを検索したい場合は、オブジェクトまたはその型に対して実行できます。ただし、どちらのオプションも正しくないようです。
def lookup_add(o):
return o.__add__
def lookup_sub(o):
return type(o).__sub__
class Foo(type):
def __add__(self, other):
return NotImplemented
def __sub__(self, other):
return NotImplemented
class Bar(object):
__metaclass__ = Foo
def __add__(self, other):
return NotImplemented
baz = Bar()
lookup_add(Bar) # Produces wrong method
lookup_sub(baz) # Should raise an error. Instead, produces wrong method.
lookup_add
オブジェクトで調べます。に対しては正しく機能し、 のlookup_add(baz)
メソッドに対してバインドされたメソッド オブジェクトを返しますが、 に対してbaz
は間違った結果を生成しlookup_add(Bar)
ます。
lookup_sub
タイプで調べます。に対しては正しく機能し、 のlookup_sub(Bar)
メソッドに対してバインドされていないメソッド オブジェクトを返しますBar
が、 に対しては間違った結果を生成しlookup_sub(baz)
ます。
を試すこともできますが、実際にはのメソッドfunctools.partial(operator.add, o)
を検索しません。が実際に実装されていないo
場合、この試みは私が望むエラーを生成しません。o
__add__
インタープリターの特別なメソッド検索動作を再現する良い方法はありますか?