Python与define相当
我在ruby中有这样的代码:
class Package
def initialize(name)
@name = name
@elements = []
end
[:type, :block].each do |bindtype|
define_method "get_#{bindtype}_by_name" do |name|
get_by_name(name, bindtype)
end
end
def get_by_name(name, bindtype=nil)
@elements.each do |element|
return if element.name == name
end
return nil
end
我已经阅读了关于python中的define_method的这个问题,我想用我的Ruby代码在Python中实现同样的事情:
bindtypes = {"type", "block"}
class Package:
def __init__(self, name):
self.name = name
self.elements = list()
def get_by_name(self, name, bindtype=None):
for element in self.elements:
if element.name == name:
return element
return None
for bindtype in bindtypes:
def _in_bindtype(self, bindtype, bindtype):
Package.get_by_name(bindtype, bindtype)
setattr(Package, "get_"+bindtype+"_by_name", _in_bindtype
我调用这样的函数:
package = Package("package")
block = Block("blockName")
package.elements.append(block)
blockFound = package.get_block_by_name(block.name, block.bindtype)
但显然这不起作用,因为我没有恢复我正在搜索的元素的名称。 有人可以帮助我更好地了解这个python define_method如何处理我的代码?
你几乎在那里; 绑定bindtype
值作为函数参数的默认值,并且您想在self
上调用get_by_name()
:
for bindtype in bindtypes:
def _in_bindtype(self, name, bindtype=bindtype):
self.get_by_name(name, bindtype)
setattr(Package, "get_{}_by_name".format(bindtype), _in_bindtype)
我冒昧地使用str.format()
来格式化方法名称,而不是使用+
连接,我发现它更具可读性。
或者,在Python 3中,您可以创建functools.partialmethod()
对象:
from functools import partialmethod
for bindtype in bindtypes:
setattr(Package, "get_{}_by_name".format(bindtype),
partialmethod(Package.get_by_name, bindtype=bindtype))
链接地址: http://www.djcxy.com/p/31699.html
上一篇: Python's equivalent for define
下一篇: Is there a way to rewrite a list comprehension as a for loop?