如何在python中重定向方法调用?

时间:2020-04-22 20:14:28

标签: python oop

我知道您可以使用__getattr__()来访问不存在的属性,这些属性不是该类的属性。但是我想对函数做同样的事情。

我读到python对待属性和方法相同,因此您也将__getattr__()用于方法。这是真的吗?

class container:
    def __init__(self, data):
        self.data = data

    def __getattr__(self, item):
        ##Don't know the code to put here vv
        result = getattr(self.data, item)


class data:
    def printHello(self):
        print("hello")

    def printString(self, string):
        print(string)

def main():
    someData = data()
    someContainer = container(someData)
    someContainer.printString("sup")

main()

目标:我希望能够编写container.printHello()并使其调用container.data.printHello()。我还需要一种能够将参数也传递给printString()的解决方案。我将如何去做?

注意:这是一种简化。实际上,我有很多方法,在开发程序时会不断添加,删除和更改方法名称

3 个答案:

答案 0 :(得分:3)

您几乎拥有了它,您只需要返回

class Container:
    def __init__(self, data):
        self.data = data
    def __getattr__(self, attr):
        return getattr(self.data, attr)

class Data:
    def print_hello(self):
        print("hello")

    def print_string(self, string):
        print(string)


Container(Data()).print_hello()
Container(Data()).print_string('foo')

答案 1 :(得分:2)

也许您忘记了返回结果?对我有用:

def __getattr__(self, item): 
    return getattr(self.data, item)

答案 2 :(得分:1)

您需要做的就是返回找到的属性。

"""
Tests

>>> c = container(data())
>>> c.printHello()
hello
>>> c.printString("Hello World")
Hello World
>>> c.printGarbage('Hello World')
Traceback (most recent call last):
  File "cont.py", line 19, in __getattr__
    result = getattr(self.data, item)
AttributeError: 'data' object has no attribute 'printGarbage'
"""

import functools

class container:
    def __init__(self, data):
        self.data = data

    def __getattr__(self, item):
        result = getattr(self.data, item)
        return result

class data:
    def printHello(self):
        print("hello")

    def printString(self, string):
        print(string)