摆脱BoundedNumericProperty错误处理程序中的幻数

时间:2019-06-12 23:39:24

标签: python kivy

我是刚开始使用BoundedNumericProperty。 我需要将变量“ saturation”的值限制为0到1,这样,如果我尝试将值设置为大于1,则将得到1;如果小于0,则将为0。

我了解到可以这样做:

saturation = BoundedNumericProperty (
                            0.1,
                            min = 0,
                            max = 1.,
                            errorhandler = lambda x: min (max (x, 0), 1))

此代码可以正常工作,但是由于错误处理程序而不够方便。

您可以看到问题是我在错误处理程序中有不必要的幻数(0和1),它们重复了最小和最大参数值。

我查看了在Github上使用BoundedNumericProperty的不同示例,并且几乎在所有示例中都看到了这一点。

相反,我想简单地写一些类似的东西:

saturation = MyProperty (
                            0.1,
                            min = 0,
                            max = 1.,)

,我希望此属性以这种方式工作:

class MyProperty(BoundedNumericProperty): 
    def __init__(*args, min=0, max=1, **kwargs):
         super().__init__(*args, min=min, max=max, errorhandler=lambda x: min(max(x, min), max), **kwargs)

但是我得到了

super().__init__(*args, min=min, max=max, errorhandler=lambda x: min(max(x, min), max), **kwargs)
 RuntimeError: super(): no arguments

(python3)

如何实现?

1 个答案:

答案 0 :(得分:0)

这似乎可行

#include <string.h>
#include <stdlib.h>
int fat(int x)
{
    if (x == 0 || x == 1)
    {
        return 1;
    }
    else
    {
        return x * fat(x-1);
    }
}

int main()
{
    int n, i, f=0, arr[30];
    char str[30];
    printf("Type the value of N: ");
    scanf("%d",&n);
    for (i=1;i<=n;i++)
    {
        f = fat(i);
    }
    printf("%d \n", f);
    sprintf(str, "%d", f);
    n=0;
    for (i=0;i<strlen(str);i++)
    {
        arr[i]=atoi(str[i]);
        n=n+arr[i];
    }
    printf("%d", n);
}

另一个示例(不使用lambda):

class MyProperty(BoundedNumericProperty):
    def __init__(self, *largs, **kw):
        my_min = kw.get('min', 0)  # 0 is default
        my_max = kw.get('max', 1)  # 1 is default
        kw['min'] = my_min
        kw['max'] = my_max
        kw['errorhandler'] = lambda x: min(max(x, my_min), my_max)
        super().__init__(*largs, **kw)