decorate a python class such that most methods raise an exception if condition

car*_*mom 4 python oop class decorator python-3.x

我曾遇到过这样的情况:如果某个条件为,则除一个方法外,大多数类的方法都需要引发异常False。可以进入大多数方法并编写if not condition,以便在条件不成立的情况下每个方法都将引发异常,但是我认为可以用类顶部的单个装饰器以某种方式进行此操作。

这个问题是相似的,但是它涉及到分别装饰每个方法,如果我要这样做,那么最好将if语句放入每个方法中。

这是一些代码和注释,以帮助进行交流:

CONDITION = True  # change to False to test

def CheckMethods():
    if CONDITION:
        # run all the methods as usual if they are called
        pass 
    else:
        # raise an exception for any method which is called except 'cow'
        # if 'cow' method is called, run it as usual
        pass


@CheckMethods
class AnimalCalls:
    def dog(self):
        print("woof")
    def cat(self):
        print("miaow")
    def cow(self):
        print("moo")
    def sheep(self)
        print("baa") 

a = AnimalCalls()
a.dog()
a.cat()
a.cow()
a.sheep()
Run Code Online (Sandbox Code Playgroud)

有谁知道如何做到这一点?从未装饰过一个类,也从未尝试过检查此类方法。

kay*_*kay 5

实现代理就这么简单

class Proxy:
    def __init__(self, inst):
        self.__inst = inst

    def __getattr__(self, name):
        return getattr(self.__inst, name)
Run Code Online (Sandbox Code Playgroud)

代替obj = SomeClass()您使用obj = Proxy(SomeClass())obj.attribute被拦截的所有访问Proxy.__getattr__。那就是您可以添加更多逻辑的方法,例如:

class MethodChecker:
    def __init__(self, inst, check):
        self.__inst = inst
        self.__check = check

    def __getattr__(self, name):
        self.__check()
        return getattr(self.__inst, name)
Run Code Online (Sandbox Code Playgroud)