【问题标题】:Python dispatching attribute access to embeded objectPython调度属性访问嵌入对象
【发布时间】:2014-06-10 17:48:59
【问题描述】:

我有一个类似的课程:

class C(object):

    _use_obj = 'attr1 attr2'.split()

    def __init__(self, obj):
        self.obj = obj

    # class definition continues here defining a few attributes and methods

我希望能够通过C通过一定的规则访问obj的属性。

c.this 应该返回:

  1. obj.this 如果thisC._use_obj
  2. C.this 如果thisC 中定义
  3. obj.this 如果this 未在C 中定义

this 可以是属性(类或实例)、属性或方法。而且我事先不知道myobj是什么。在没有规则 1 的情况下,我想我可以用 __getattr__ 做到这一点。但是对于规则 1,我不清楚,因为我需要拦截所有属性访问。

【问题讨论】:

  • 我不明白为什么您认为规则 1 意味着您不能使用 __getattr__。你能再解释一下吗?
  • @BrenBarn 因为如果thisC 中定义,则不会调用__getatrr__
  • 这可能有助于更新您的示例,以便它实际显示问题。您的示例C 没有任何与_use_obj 中定义的属性重叠的属性。无论如何,您仍然可以使用__getattribute__

标签: python properties attributes


【解决方案1】:

您可以使用__getattribute__ 拦截所有 属性访问,但如果您没有匹配的属性,则需要小心将控制权交给被覆盖的方法。 所有属性访问都是通过这个方法处理的,需要注意不要陷入无限递归循环:

class C(object):
    _use_obj = 'attr1 attr2'.split()

    def __init__(self, obj):
        self.obj = obj

    def __getattribute__(self, name):
        # setup, make it easier to get attributes we need
        get = super(C, self).__getattribute__
        use_obj = get('_use_obj')
        obj = get('obj')

        if name in use_obj:
            # rule 1, attribute is specifically listed
            return getattr(obj, name)
        try:
            # rule 2, try attribute on self
            return get(name)
        except AttributeError:
            # rule 3, fall back to self.obj
            return getattr(obj, name)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多