简体   繁体   English

动态地使用装饰器从类外部添加方法

[英]Dynamicaly add methods from outside the class with a decorator

Two things I'm having trouble with. 我遇到麻烦的两件事。 Adding a method from outside that references self. 从外部添加引用self的方法。 ie

class A(object):
  def __init__(self, name): 
    self.name=name

def my_name_is(self):
  print("my name is %s" %(self.name))

setattr(A, my_name_is.__name__, classmethod(my_name_is))
a = A('bob')
a.my_name_is() 

Because it tries to reference the name attr of 'A' rather than 'a'. 因为它试图引用'A'的名称attr而不是'a'。

The other one is adding the function with a decorator ie something like a 另一个是使用装饰器添加函数,例如a

@addMethod(A)
def say_hello_to(x):
  print("hello %s" %x)

rather some kind of equivalent to 相当于某种等价物

def addMethod(cls, f) 
  setattr(cls, f.__name__, classmethod(f))

Question 1 : what you're looking for is a method, not classmethod . 问题1 :您正在寻找的是一种方法,而不是classmethod In this case, a simple assignment would work: 在这种情况下,一个简单的赋值可以工作:

A.my_name_is = my_name_is

Question 2 : the expression following the @ should return a callable, ie addMethod(A) should be a callable. 问题2@下面的表达式应返回一个可调用的,即addMethod(A)应该是可调用的。 This can be done like this: 这可以这样做:

def addMethod(cls):
  def method_assigner(f):
     setattr(cls, f.__name__, f)
     return f
  return method_assigner

Then this works: 然后这工作:

@addMethod(A)
def say_hello_to(x):
  print("hello %s" %x)

(In this example, x will get the value of self when say_hello_to is called. I'm not sure I understand exactly the role of x in your cas, but hopefully this makes it clear how to achieve what you want. Perhaps you want def say_hello_to(self, x):... ?). (在这个例子中,当say_hello_to时, x将获得self的值。我不确定我是否完全理解x在你的cas中的作用,但希望这能清楚地表明如何实现你想要的。也许你想要def say_hello_to(self, x):... ?)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM