如何将Python程序移植到Ruby
我试图将Python程序移植到Ruby,但我对Python一无所知 你能给我一些建议吗 我想运行如何将Python程序移植到Ruby,python,ruby,Python,Ruby,我试图将Python程序移植到Ruby,但我对Python一无所知 你能给我一些建议吗 我想运行sampletrain方法。但是,我不明白为什么features=self.getfeatures(item)可用getfeatures只是一个实例变量,不是吗?它似乎被用作一种方法 : 在Python中,由于方法调用的括号不是可选的,所以可以区分方法引用和方法调用。i、 e def example(): pass x = example # x is now a reference to
sampletrain
方法。但是,我不明白为什么features=self.getfeatures(item)
可用getfeatures
只是一个实例变量,不是吗?它似乎被用作一种方法
:
在Python中,由于方法调用的括号不是可选的,所以可以区分方法引用和方法调用。i、 e
def example():
pass
x = example # x is now a reference to the example
# method. no invocation takes place
# but later the method can be called as
# x()
vs
因为方法调用的括号在Ruby中是可选的,所以您需要使用一些额外的代码,例如
x=method(:example)
和x.call
来实现相同的功能。在Python中,因为方法调用的括号不是可选的,所以可以区分方法引用和方法调用。i、 e
def example():
pass
x = example # x is now a reference to the example
# method. no invocation takes place
# but later the method can be called as
# x()
vs
因为方法调用的括号在Ruby中是可选的,所以您需要使用一些额外的代码,例如x=method(:example)
和x.call
来实现相同的功能。Ruby中发送行为的惯用方法(因为代码中的getfeatures
显然是可调用的)是使用块:
class Classifier
def initialize(filename = nil, &getfeatures)
@getfeatures = getfeatures
...
end
def train(item, cat)
features = @getfeatures.call(item)
...
end
...
end
Classifier.new("my_filename") do |item|
# use item to build the features (an enumerable, array probably) and return them
end
Ruby中发送行为的惯用方法(因为代码中的getfeatures
显然是可调用的)是使用块:
class Classifier
def initialize(filename = nil, &getfeatures)
@getfeatures = getfeatures
...
end
def train(item, cat)
features = @getfeatures.call(item)
...
end
...
end
Classifier.new("my_filename") do |item|
# use item to build the features (an enumerable, array probably) and return them
end
如果您是从Python进行翻译,那么您必须学习Python,这样您就不会对它“完全无知”。没有捷径。如果你要从Python翻译,你必须学习Python,这样你就不会对它“完全无知”。没有捷径。这里有一个猜测:也许在初始化过程中传入的第二个参数是一个函数;虽然它在初始化期间被分配给属性,但稍后可以使用paren调用它。(这类似于JavaScript,但不是Python。)@ThiefMaster和steenslag:)只是为了工作。。谢谢你的评论。@Phrogz“类似于JS”对我来说很容易理解。Thanksher猜测:也许在初始化过程中传入的第二个参数是一个函数;虽然它在初始化期间被分配给属性,但稍后可以使用paren调用它。(这类似于JavaScript,但不是Python。)@ThiefMaster和steenslag:)只是为了工作。。谢谢你的评论。@Phrogz“类似于JS”对我来说很容易理解。感谢您应该能够使用我上面给出的样式或编写
initialize
来接受tokland建议的块,这取决于您可能希望为getfeatures
功能提供命名方法还是匿名块。如果您需要更多详细信息,请告诉我。您应该能够使用我上面给出的样式或编写initialize
来接受tokland建议的块,这取决于您可能希望为getfeatures
功能提供命名方法还是匿名块。如果你需要更多的细节,请告诉我。