Python 将当前类传递给decorator函数

Python 将当前类传递给decorator函数,python,types,decorator,typechecking,python-decorators,Python,Types,Decorator,Typechecking,Python Decorators,我有一个decorator方法来检查传递给函数的参数类型 def接受(*类型): def检查_接受(f): 断言len(类型)==f.func\u code.co\u argcount def new_f(*参数,**kwds): 对于zip中的(a,t)(参数,类型): 断言存在(a,t)\ “参数%r与%s不匹配”%(a,t) 返回f(*args,**kwds) 新建函数名称=函数名称 返回新的 退票 现在,在一个类中(在classA.py中),我想要一个只接受相同类的参数的方法: A类:

我有一个decorator方法来检查传递给函数的参数类型

def接受(*类型):
def检查_接受(f):
断言len(类型)==f.func\u code.co\u argcount
def new_f(*参数,**kwds):
对于zip中的(a,t)(参数,类型):
断言存在(a,t)\
“参数%r与%s不匹配”%(a,t)
返回f(*args,**kwds)
新建函数名称=函数名称
返回新的
退票
现在,在一个类中(在
classA.py
中),我想要一个只接受相同类的参数的方法:

A类:
@接受(什么放在这里)
def剂量测量(其他对象):
#做点什么

在其他类中,我可以将
ClassA
放在
whatput
的位置,但在
ClassA.py
中,
ClassA
是未知的。如何将当前类传递给
@accepts()
函数?

使用基于函数的装饰器版本,并在类定义后应用它:

class ClassA:
    def doSomething(otherObject):
        # Do something
ClassA.doSomething = accepts(ClassA)(ClassA.doSomething)
另一种方法是编写一个在类创建后自动应用此方法的:

class Meta(type):

    def __new__(cls, clsname, bases, dct):
       fields = ('doSomething', ) #Fields on which you want to apply the decorator
       for name, val in dct.items():
           if name in fields:
               dct[name] = accepts(cls)(val)
       return type.__new__(cls, clsname, bases, dct)


class ClassA(object):
    __metaclass__ = Meta
    def doSomething(otherObject):
        pass

不要手动执行诸如
new\u f.func\u name=f.func\u name
之类的操作,而是使用。这还将保留文档字符串、参数列表等内容

from functools import wraps
def accepts(*types):
    def check_accepts(f):
        print "inside"
        assert len(types) == f.func_code.co_argcount
        @wraps(f)
        def new_f(*args, **kwds):

self
变量添加到函数
doSomething
中,然后在
check\u accepts
中引用
args[0]
(前提是在定义中添加
(*args)
或额外参数)难道不能解决您的问题吗?如果函数
doSomething
应该是一个类方法,您仍然可以将该
self
外包。怎么做

  • self
    添加到类内的某个伪方法中
  • 制作一个装饰器,填充
    接受的
    可以以某种方式到达的变量(如元数据)
  • 确保在调用
    doSomething()
  • 你得到了类实例!享受吧

注意:这不是存储这样的元数据并在以后使用的唯一方法,您可以按照自己的意愿执行。

对不起,我不知道您的意思。这不是我的意图,不。你能解释一下为什么会发生这种情况吗?人力资源管理,想想看,这不会发生在这里;您已经重新实现了与Python2中的方法相同的类型检查;强制
self
为当前类的相同类型或子类。但是看起来好像你没有考虑到
args[0]
在这里是
self