如何处理使用__getattr__函数返回Python类中缺少的属性和函数? [英] How to handle & return both properties AND functions missing in a Python class using the __getattr__ function?

查看:189
本文介绍了如何处理使用__getattr__函数返回Python类中缺少的属性和函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python类上使用__getattr__特殊方法来处理缺少的属性或函数相当容易,但似乎不能同时处理两者.

It is fairly easy to use the __getattr__ special method on Python classes to handle either missing properties or functions, but seemingly not both at the same time.

请考虑以下示例,该示例处理未在类的其他位置明确定义的任何请求的属性...

Consider this example which handles any property requested which is not defined explicitly elsewhere in the class...

class Props:
    def __getattr__(self, attr):
        return 'some_new_value'

>>> p = Props()
>>> p.prop                          # Property get handled
'some_new_value'

>>> p.func('an_arg', kw='keyword')  # Function call NOT handled
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'str' object is not callable

接下来,考虑这个示例,该示例处理未在类中其他位置显式定义的任何函数调用...

Next, consider this example which handles any function call not defined explicitly elsewhere in the class...

class Funcs:
    def __getattr__(self, attr):
        def fn(*args, **kwargs):
            # Do something with the function name and any passed arguments or keywords
            print attr
            print args
            print kwargs
            return 
        return fn

>>> f = Funcs()
>>> f.prop                          # Property get NOT handled
<function fn at 0x10df23b90>

>>> f.func('an_arg', kw='keyword')  # Function call handled
func
('an_arg',)
{'kw': 'keyword'}

问题是如何在同一__getattr__中处理两种类型的缺失属性?如何检测所请求的属性是在属性符号中还是在带括号的方法符号中,并分别返回值或函数?本质上,我想处理一些缺少的属性属性和一些缺少的函数属性,然后在所有其他情况下求助于默认行为.

The question is how to handle both types of missing attributes in the same __getattr__? How to detect if the attribute requested was in property notation or in method notation with parentheses and return either a value or a function respectively? Essentially I want to handle SOME missing property attributes AND SOME missing function attributes and then resort to default behavior for all the other cases.

建议?

推荐答案

如何检测所请求的属性是在属性符号中还是在带括号的方法符号中,并分别返回值或函数?

How to detect if the attribute requested was in property notation or in method notation with parentheses and return either a value or a function respectively?

不能.您也无法分辨所请求的方法是实例,类还是静态方法等.您所能知道的只是有人试图检索属性以进行读取访问.没有其他任何东西传递到getattribute机制中,因此您的代码没有其他可用的东西.

You can't. You also can't tell whether a requested method is an instance, class, or static method, etc. All you can tell is that someone is trying to retrieve an attribute for read access. Nothing else is passed into the getattribute machinery, so nothing else is available to your code.

因此,您需要一些带外方法来了解是创建一个函数还是某种其他类型的值.这实际上很常见-您可能实际上是在为具有值/功能区别(例如ctypes或PyObjC)的其他对象的代理,或者您可能具有命名约定等.

So, you need some out-of-band way to know whether to create a function or some other kind of value. This is actually pretty common—you may actually be proxying for some other object that does have a value/function distinction (think of ctypes or PyObjC), or you may have a naming convention, etc.

但是,您始终可以返回一个可以以任何一种方式使用的对象.例如,如果您的默认行为"是返回属性为整数或返回整数的函数,则可以返回以下内容:

However, you could always return an object that can be used either way. For example, if your "default behavior" is to return attributes are integers, or functions that return an integer, you can return something like this:

class Integerizer(object):
    def __init__(self, value):
        self.value = value
    def __int__(self):
        return self.value
    def __call__(self, *args, **kw):
        return self.value

这篇关于如何处理使用__getattr__函数返回Python类中缺少的属性和函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆