Python:如果某个属性为true,则允许调用某些方法

Python:如果某个属性为true,则允许调用某些方法,python,functional-programming,Python,Functional Programming,我试图防止类中某些方法的使用被滥用。我想一个警卫装饰师可以做如下工作 例如,我们有classHello。它有一个属性allowed和两个方法allowed\u function和disallowed\u function。守卫装饰器将管理哪些函数可以调用,哪些函数不能调用 class Hello: def __init__(self): self.allowed = True def guard_func(self): return(self.a

我试图防止类中某些方法的使用被滥用。我想一个警卫装饰师可以做如下工作

例如,我们有class
Hello
。它有一个属性
allowed
和两个方法
allowed\u function
disallowed\u function
。守卫装饰器将管理哪些函数可以调用,哪些函数不能调用

class Hello:
    def __init__(self):
        self.allowed = True

    def guard_func(self):
        return(self.allowed)

    @guard(guard_func)
    def allowed_function(self):
        print "I'm allowed!"

    @guard(not guard_func)
    def disallowed_function(self):
        print "I'm not allowed!"

我应该如何在Python中实现这一点?

这里是Python3的
guard
实现(看起来您可能正在使用2;我强烈建议升级)

基本上,这里需要两个间接层次。您必须编写一个返回实际decorator函数的函数,以便在实际使用decorator时根据传入的条件函数对其进行参数化。您还需要注意如何传递
self


functools.wrapps是不必要的,但强烈建议:


上面的所有内容都应该像Python 2上宣传的那样工作,您只需要用字符串格式替换f字符串。

由@JoshKarpel实现的
guard
decorator似乎很好

但是,我建议您稍微改变一下设计:

class Hello:
    def __init__(self):
        self.group1_enable = True
        self.group2_enable = False

    def group1(self):
        return(self.group1_enable)
    def group2(self):
        return(self.group2_enable)

    @guard(group1)
    def allowed_function(self):
        print "I'm allowed!"

    @guard(group2)
    def disallowed_function(self):
        print "I'm not allowed!"

此设计允许独立启用和禁用多组功能。

您的意思是让装饰器在每个实例中工作吗?
class Hello:
    def __init__(self):
        self.group1_enable = True
        self.group2_enable = False

    def group1(self):
        return(self.group1_enable)
    def group2(self):
        return(self.group2_enable)

    @guard(group1)
    def allowed_function(self):
        print "I'm allowed!"

    @guard(group2)
    def disallowed_function(self):
        print "I'm not allowed!"