[英]Python: dynamically create methods based on other classes'
I've looked for quite a while but couldn't find a proper answer to my question: I have a class containing methods which operate on arrays and I want dynamically create methods with a similar name in another class with a modified output. 我已经寻找了很长时间,但找不到我的问题的正确答案:我有一个包含对数组进行操作的方法的类,并且我想在另一个具有修改后的输出的类中动态创建名称相似的方法。
I've got something like this so far, can anyone guide me ? 到目前为止,我有这样的事情,有人可以指导我吗?
Class A():
def__init__(self,array):
self.data = array
def method1(self,*args):
newarray = whatever(self.data,*args)
return newarray
def method2(self,*args):
newarray = whatever2(self.data,*args)
return newarray
I want to be able to use those methods to generate new ones in a more complex class, say: 我希望能够使用这些方法在更复杂的类中生成新方法,例如:
class B(C): #inherits from C
def __init__(self,[arg1,array]):
#initialize from parent class
C.__init__(self,[arg1,array])
#create new methods for this class using same name
methodnames = [element for element in dir(A) if element[0] != '_']
for methodname in methodnames:
##following works but this is not the output I want here
#self.__dict__[methodname] = getattr(A(array),methodname)
#following doesn't work... at least not as I expect it to
#case1
#self.__dict__[methodname] = [arg1,getattr(A(array),methodname)]
#case2
self.__dict__[methodname] = list([arg1,getattr(A(array),methodname)])
a = array
#following returns a list of [arg1, method] but what I really want is [arg1,newarray]
C([arg1,array]).method1(*args)
OK, so let's try to be clearer: 好的,让我们尝试更加清晰:
Class A contains filters, takes an array and applies filter as method, returns filtered data. A类包含过滤器,采用数组并将过滤器作为方法,返回过滤后的数据。
Class filters() 类filter()
def__init__(self,array):
self.data = array
def filter1(self,*args):
newarray = median(self.data,*args)
return newarray
def filter2(self,*args):
newarray = gaussian(self.data,*args)
return newarray
...
In another module, I have class SpecialData, which operates on a list of x,y data (where x and y are iterables, ie lists, arrays...). 在另一个模块中,我有SpecialData类,该类对x,y数据列表进行操作(其中x和y是可迭代的,即列表,数组...)。 So something like
所以像
Class SpecialData(): 类SpecialData():
def __init__(self,[x,y]):
self.data = [x,y]
def power(self,power):
ypow = self.data[1]**power
return [x,pow]
def porod(self):
return [x**4,x**4*y]
....
Now, what I want is to add the filter methods contained in class filters to class SpecialData. 现在,我想要的是将类过滤器中包含的过滤器方法添加到SpecialData类中。 I could, of course do this by re-coding all filters with proper format for SpecialClass.
我当然可以通过使用SpecialClass的正确格式重新编码所有过滤器来做到这一点。 but what I really want, is that each time a new filter is added to class filters, to make it available at runtime in class SpecialData without having to re-hard code the new filter.
但我真正想要的是,每次将新过滤器添加到类过滤器时,即可在运行时在SpecialData类中使用它,而不必重新对新过滤器进行硬编码。
So, not being very clever, I tried to read the list of available filters in class filters by: 因此,不是很聪明,我尝试通过以下方式读取类过滤器中可用过滤器的列表:
import filters 导入过滤器
filternames = [element for element in dir(filters) if element[0] != '_'] filternames = [如果元素[0]!='_',则dir(过滤器)中元素的元素]
for fitlername in filternames: generate_filters_in_class_SpecialClass 过滤器名称中的拟合器名称:generate_filters_in_class_SpecialClass
How do I do this properly ? 如何正确执行此操作?
I found a number of posts related to this, some using super(), others using SpecialData. 我发现了许多与此相关的帖子,有些使用super(),有些使用SpecialData。 dict or even setattr.
dict甚至setattr。 Since the 2nd seemed more understandable to me, I focused on this one and came up with:
由于第二个对我来说更容易理解,因此我专注于此,并提出了:
import filters 导入过滤器
Class SpecialData(): 类SpecialData():
def __init__(self,[x,y]):
self.data = [x,y]
filternames = [element for element in dir(filters) if element[0] != '_']
for fitlername in filternames:
self.__dict__[fitlername ] = [self.data[0],getattr(filters(self.data[1]),fitlername)]
Of course, this doesn't work, because the list is not callable. 当然,这是行不通的,因为该列表不可调用。 If I change the last line to : self.
如果我将最后一行更改为:self。 dict [fitlername ] = list([self.data[0],getattr(filters(self.data[1]),fitlername)]) it returns the method as the 2nd element, rather than the result.
dict [fitlername] = list([self.data [0],getattr(filters(self.data [1]),fitlername)])它返回方法作为第二个元素,而不是结果。
Note that the following works, but this is not what I want... self. 请注意以下工作,但这不是我想要的...自我。 dict [fitlername ] = getattr(filters(self.data[1]),fitlername)
字典 [fitlername] = getattr(filters(self.data [1]),fitlername)
Hope this is clearer now... 希望现在更清楚...
I think you are trying to make an advanced use of Python without using/knowing its advanced features, like you are borrowing techniques from another language. 我认为您正在尝试不使用/不了解Python的高级功能而对Python进行高级使用,就像您从另一种语言中借用了技术一样。
This is not a criticism, but you should have a look on Python tutorial , Python introspection or metaclasses . 这并不是批评,但是您应该看一下Python教程 , Python自省或元类 。
I think that if you just complete your knowledge on Python functions you will be easily able to solve your problem in a much simpler way. 我认为,如果您只了解Python函数,那么您将能够以更简单的方式轻松解决问题。
Rather than generating a proposed solution, you should make it clearer what you are trying to achieve. 与其生成提议的解决方案,不如让其更清楚地说明您要实现的目标。 Class A is a clear example of the starting point;
A类是起点的明显例子; please post an example of your desired ending point, eg
请发布您想要的终点的示例,例如
Class B():
def__init__(self,array):
self.data = array
def method1(self,*args):
newarray = ComplexWhatever(self.data,*args)
return newarray
def method2(self,*args):
newarray = EvenBiggerWhatever2(self.data,*args)
return newarray
a = A(input_array)
b = B(input_array)
print(a.method1(args))
print(b.method1(args))
What isn't clear is how you want to "dynamically generate" the new function "ComplexWhatever()" instead of writing the function by hand. 还不清楚您想如何“动态生成”新函数“ ComplexWhatever()”,而不是手动编写函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.