【问题标题】:What would be better way if any to store list of methods that would be easily accessible?如果有存储易于访问的方法列表的更好方法是什么?
【发布时间】:2019-08-14 20:33:34
【问题描述】:

我有一个有多个方法的类,我想存储所有可用的方法,这些方法在示例中很容易访问,就像这样

class Methods:
    def foo(self, a):
        return f'hello {a}' 


    def bar(self, b):
        return f'hello {b}'

    def methods_dict(self, var, **kwargs):
        dic = {
            'me' : self.foo(var),
            'be': self.bar(var)
        }
    return dic

但在运行时,我的 methods_dict() 方法将执行其字典中的两个方法。 一方面我打算只在其中存储字符串并且它真的很容易访问,另一方面我可能不需要一次访问所有可用的方法。

有什么建议吗?

我打算如下使用这些方法

class InheritMethods(Methods):
        def __init__(self, method_name):
            self.method_name = method_name

        def add_to_list(self, input):
            arr = []
            arr.append(self.method_dicts(input)[self.method_name]
            return arr

为了清楚起见,我会根据输入的名称调用特定的方法,所以基本上是input == method_name
我可以做像if input == 'foo': do somethings.. 这样的条件语句,但是如果我最终有很多方法,我的代码会一团糟,所以我假设(!)这不是一个好主意

【问题讨论】:

  • 你刚刚为自己发明了一个问题。我看不出有什么原因
  • 你可以做lambda _: self.foo(var),或者直接返回self.foo
  • @hilberts_drinking_problem 不,你不能,foo 是一个类的方法,不在methods_dict 的范围内,你需要{'foo': self.foo}
  • @LaurensKoppenol 我的错,我看错了帖子。也许functools.partial 是合适的,如果有的话。
  • 如果有更多的可选参数是个好主意

标签: python oop


【解决方案1】:

我认为你可以通过以下方式得到你想要的。您的确切用例仍不清楚。如果我走错了方向,请回复。

使用self.__getattribute__() 可以通过名称获取函数。当然,您必须捕获异常等。

class Methods:
    def foo(self, a):
        return f'hello {a}' 

    def bar(self, b):
        return f'hello {b}'

class InheritMethods(Methods):
    def __init__(self, method_name):
        self.method_name = method_name

    def add_to_list(self, method_name, input):
        method = getattr(self, method_name)
        result = method(input)
        return [result]

class InheritSingleMethod(Methods):
    def __init__(self, method_name):
        self.add_to_list = self.getattr(self, method_name)

输出

# Any method version
inherit_methods = InheritMethods('a')  # < no use for that argument right?
inherit_methods.add_to_list('foo', 'laurens')
> ['hello laurens']

# Single method version
inherit_single_method = InheritSingleMethod('foo')
inherit_single_method.add_to_list('laurens')
> 'hello laurens'

【讨论】:

  • 天哪,我正在考虑使用 getattr() 的解决方案,但事实并非如此。这样可行 !谢谢(:
  • 其实,对你的代码有一点改进,我们可以传递self.method_name而不是在add_to_list()中创建额外的参数,因为我们无论如何都要实例化method_name
  • 除非你参考Guido van Rossum,否则领主不擅长python。实际上,他一般不太擅长蛇。
  • 如果您只想在add_to_list 中使用1 个单一功能,请查看上面的InheritSingleMethod
  • 您为什么使用self.__getattribute__(method_name) 而不仅仅是getattr(self, method_name)?后者似乎没有那么神奇!
【解决方案2】:

如果您只想访问给定 str 中的名称的 Methods 方法,请使用 getattr

name = input()
m = Methods()
getattr(m, name)("bob")

【讨论】:

    猜你喜欢
    • 2013-09-20
    • 2019-06-27
    • 2019-03-11
    • 2017-02-01
    • 2011-06-05
    • 2012-09-02
    • 2014-05-03
    • 2011-01-09
    • 2021-02-23
    相关资源
    最近更新 更多