确定__getattr__是方法调用还是属性调用 [英] Determine if __getattr__ is method or attribute call
问题描述
有什么方法可以确定使用__getattr__的方法和属性调用之间的区别吗?
Is there any way to determine the difference between a method and an attribute call using __getattr__?
即在:
class Bar(object):
def __getattr__(self, name):
if THIS_IS_A_METHOD_CALL:
# Handle method call
def method(**kwargs):
return 'foo'
return method
else:
# Handle attribute call
return 'bar'
foo=Bar()
print(foo.test_method()) # foo
print(foo.test_attribute) # bar
这些方法不是本地的,因此无法使用getattr/callable确定它.我也理解方法是属性,并且可能没有解决方案.只是希望有一个.
The methods are not local so it's not possible to determine it using getattr/callable. I also understand that methods are attributes, and that there might not be a solution. Just hoping there is one.
推荐答案
您根本无法确定在__getattr__
挂钩中将如何使用对象.例如,您可以在不调用方法的情况下访问方法,将它们存储在变量中,然后稍后对其进行调用.
You cannot tell how an object is going to used in the __getattr__
hook, at all. You can access methods without calling them, store them in a variable, and later call them, for example.
使用__call__
方法返回对象,该对象将在调用时被调用:
Return an object with a __call__
method, it'll be invoked when called:
class CallableValue(object):
def __init__(self, name):
self.name = name
def __call__(self, *args, **kwargs):
print "Lo, {} was called!".format(self.name)
class Bar(object):
def __getattr__(self, name):
return CallableValue(name)
但是此实例与字符串或列表不同.
but instances of this will not be the same thing as a string or a list at the same time.
演示:
>>> class CallableValue(object):
... def __init__(self, name):
... self.name = name
... def __call__(self, *args, **kwargs):
... print "Lo, {} was called!".format(self.name)
...
>>> class Bar(object):
... def __getattr__(self, name):
... return CallableValue(name)
...
>>> b = Bar()
>>> something = b.test_method
>>> something
<__main__.CallableValue object at 0x10ac3c290>
>>> something()
Lo, test_method was called!
这篇关于确定__getattr__是方法调用还是属性调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!