我想迭代一个类中的方法,或者根据存在的方法以不同的方式处理类或实例对象.如何获取类方法列表?
另见:
现在很清楚元类是什么,有一个相关的概念,我一直在使用,而不知道它的真正含义.
我想每个人都用括号做错了,导致"对象不可调用"异常.更重要的是,使用__init__并__new__导致想知道这种血腥__call__可以用于什么.
你能给我一些解释,包括魔术方法的例子吗?
我真的不需要这样做,但只是想知道,有没有办法将装饰器绑定到类中的所有函数,而不是明确地为每个函数声明它.
我认为它然后变成了一种方面,而不是装饰者,它确实感觉有点奇怪,但是想到时间或认证这样的东西它会非常整洁.
今天早上我有一个有趣的问题.我有一个基类看起来像这样:
# base.py
class Base(object):
@classmethod
def exists(cls, **kwargs):
# do some work
pass
Run Code Online (Sandbox Code Playgroud)
还有一个看起来像这样的装饰模块:
# caching.py
# actual caching decorator
def cached(ttl):
# complicated
def cached_model(ttl=300):
def closure(model_class):
# ...
# eventually:
exists_decorator = cached(ttl=ttl)
model_class.exists = exists_decorator(model_class.exists))
return model_class
return closure
Run Code Online (Sandbox Code Playgroud)
这是我的子类模型:
@cached_model(ttl=300)
class Model(Base):
pass
Run Code Online (Sandbox Code Playgroud)
事实上,当我实际上调用Model.exists时,我得到关于错误数量的参数的抱怨!检查装饰器中的参数显示没有任何奇怪的事情 - 参数正是我所期望的,并且它们与方法签名匹配.如何将其他装饰器添加到已经装饰的方法中classmethod?
并非所有模型都被缓存,但exists()方法作为类方法存在于每个模型上,因此重新排序装饰器不是一个选项:cached_model可以将类方法添加到exists(),但是什么使exists()成为类方法在未缓存的模型?
我想在某些类中记录每个方法调用.我本可以做到的
class Class1(object):
@log
def method1(self, *args):
...
@log
def method2(self, *args):
...
Run Code Online (Sandbox Code Playgroud)
但是我在每个班级都有很多方法,而且我不想单独装饰每一个.目前,我尝试使用带有元类的hack(覆盖我记录的类',__getattribute__这样如果我尝试获取方法,它将返回一个日志记录方法):
class LoggedMeta(type):
def __new__(cls, name, bases, attrs):
def __getattribute__(self, name_):
attr = super().__getattribute__(name_)
if isinstance(attr, (types.MethodType, types.FunctionType)) and not name_.startswith("__"):
return makeLogged(attr) #This returns a method that first logs the method call, and then calls the original method.
return attr
attrs["__getattribute__"] = __getattribute__
return type.__new__(cls, name, bases, attrs)
class Class1(object):
__metaclass__ = LoggedMeta
def method1(self, *args):
...
Run Code Online (Sandbox Code Playgroud)
但是,我使用的是Python 2.X,而super()语法不起作用.当我调用super时,我没有__getattribute__类(但我确实有它的类名),所以我不能使用旧的超级语法super(Class, Inst). …
我遇到了一个问题,我必须对我的 API 设置返回的所有内容进行 jsonify。当我在写一个装饰器并将它应用到每一个方法时,我想到了一个想法:
“我不能只是覆盖 return 关键字,以便它每次都为我执行此操作吗?”
我进行了一些搜索,但找不到有关该主题的任何内容。然而,既然“一切都是对象”,也许有可能?
显然覆盖return是一个坏主意,但在更一般的意义上,我的问题是:
你能改变 Python 中保留字和关键字的行为吗?
python ×7
class ×2
decorator ×2
callable ×1
chaining ×1
class-method ×1
keyword ×1
logging ×1
oop ×1
python-3.x ×1
redefinition ×1
wrapper ×1