Python中的上下文相关方法 - 我做错了什么? [英] Context dependent method in Python - what am I doing wrong?

查看:140
本文介绍了Python中的上下文相关方法 - 我做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类,其f方法依赖于类的对象的模式。

I would like to create a class whose f method depends on the "mode" the object of the class has been created.

下面的代码不工作但希望它让你知道我想要做什么。我的想法是有一个字典,其中我定义每个模式的设置(在这种情况下,函数或方法分配给self.f,所以,而不是使用许多如果elif语句
在init函数中我只是使用字典分配正确的值。

The code below doesn't work but hope it gets you an idea of what I am trying to do. My idea is to have a dictionary in which I define the settings for each mode (in this case the function or method to assign to self.f, so that rather than using many if elif statements in the init function I just assign the correct values using the dictionary.

class A(object):
    _methods_dict={
            'a':A.f1,
            'b':A.f2
            }    

    def __init__(self,mode = 'a'):
        self.f = _methods_dict[mode]


    def f1(self,x):
        return x

    def f2(self,x):
        return x**2



我不知道为什么这不工作,

I can't figure why this does not work, how would you fix it? Also are there better (and more pythonic) approaches to get the same kind of functionalities?

推荐答案

商店然后使用 getattr()来检索 __ init __

class A(object):
    _methods_dict = {
        'a': 'f1',
        'b': 'f2'
    }    

    def __init__(self, mode='a'):
        self.f = getattr(self, self._methods_dict[mode])

    def f1(self, x):
        return x

    def f2(self, x):
        return x ** 2

或者,只需代理方法:

class A(object):
    _methods_dict = {
        'a': 'f1',
        'b': 'f2'
    }

    def __init__(self,mode = 'a'):
        self._mode = mode

    @property
    def f(self):
        return getattr(self, self._methods_dict[self._mode])

    def f1(self, x):
        return x

    def f2(self, x):
        return x ** 2



f 属性只返回当前模式的正确绑定方法。

The f property just returns the correct bound method for the current mode. Using a property simplifies call signature handling, and gives users the actual method to introspect if they so wish.

两种方法都有相同的结果:

Either method has the same end-result:

>>> a1 = A()
>>> a2 = A('b')
>>> a1.f(10)
10
>>> a2.f(10)
100

区别在于存储在实例,第一个方法存储绑定的方法:

The difference lies in what is stored in the instance, the first method stores bound methods:

>>> vars(a1)
{'f': <bound method A.f1 of <__main__.A object at 0x10aa1ec50>>}
>>> vars(a2)
{'f': <bound method A.f2 of <__main__.A object at 0x10aa1ed50>>}

与另一个中的方法:

>>> vars(a1)
{'_mode': 'a'}
>>> vars(a2)
{'_mode': 'b'}

很大的区别,但后一种方法创建可以酸洗和深层复制没有问题的实例。

That may not seem much of a difference, but the latter method creates instances that can be pickled and deep-copied without problems.

这篇关于Python中的上下文相关方法 - 我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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