小编mur*_*tim的帖子

"超级"对象没有调用__getattr__

我有一个物体包裹在另一个物体内."Wrapper"通过覆盖从"Wrapped"对象访问属性__getattr__.这很有效,直到我需要覆盖子类的属性,然后使用基类访问该属性super().

我仍然可以直接访问该属性,__getattr__但为什么不起作用super()

class Wrapped(object):
    def __init__(self, value):
        self.value = value

    def hello_world(self):
        print 'hello world', self.value

class Wrapper(object):
    def __init__(self, obj):
        self.wrapped_obj = obj

    def __getattr__(self, name):
        if name in self.__dict__:
            return getattr(self, name)
        else:
            return getattr(self.wrapped_obj, name)

class Subclass(Wrapper):
    def __init__(self, obj):
        super(Subclass, self).__init__(obj)

    def hello_world(self):
        # this works
        func = super(Subclass, self).__getattr__('hello_world')()
        # this doesn't
        super(Subclass, self).hello_world()

a = Wrapped(2)
b = Subclass(a)
b.hello_world()
Run Code Online (Sandbox Code Playgroud)

python getattr

17
推荐指数
1
解决办法
7866
查看次数

标签 统计

getattr ×1

python ×1