2011-11-15 17 views
1

私はPythonプログラムをRubyに移植しようとしていますが、私はPythonについて全く知らないです。PythonプログラムをRubyに移植する方法

私に助言をいただけますか?

sampletrainメソッドを実行したいです。しかし、なぜfeatures=self.getfeatures(item)が利用できるのか分かりません。 getfeaturesは単なるインスタンス変数ですね。それは方法として使われるようです。

docclass.py:Pythonで

class classifier: 
    def __init__(self,getfeatures,filename=None): 
    # Counts of feature/category combinations 
    self.fc={} 
    # Counts of documents in each category 
    self.cc={} 
    self.getfeatures=getfeatures 

    def train(self,item,cat): 
    features=self.getfeatures(item) 
    # Increment the count for every feature with this category 
    for f in features: 
     self.incf(f,cat) 

    # Increment the count for this category 
    self.incc(cat) 
    self.con.commit() 

    def sampletrain(cl): 
    cl.train('Nobody owns the water.','good') 
    cl.train('the quick rabbit jumps fences','good') 
    cl.train('buy pharmaceuticals now','bad') 
    cl.train('make quick money at the online casino','bad') 
    cl.train('the quick brown fox jumps','good') 
+1

次のように推測します。おそらく、初期化時に渡された2番目の引数は関数です。初期化中はプロパティに割り当てられますが、後で括弧で呼び出すこともできます。 (これはJavaScriptと似ていますが、Pythonではありません) – Phrogz

+0

@ThiefMasterとsteenslag :)ちょうど作業する..あなたの素敵なコメントに感謝します。 – zono

+0

@Phrogz 'JSと似ています。私にとって理解しやすいです。おかげで – zono

答えて

5

、メソッド呼び出しの括弧は、オプションではないので、方法を参照し、メソッドの呼び出しを区別することが可能です。すなわち

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() 

x = example() # calls example and assigns the return value to x 

メソッド呼び出しの括弧はRubyでオプションであるため、あなたは、例えば、いくつかの余分なコードを使用する必要がありますx = method(:example)x.callは同じことを実現します。

+0

ありがとう!私は今あなたの答えに基づいてコードを作成しようとします。 – zono

+1

あなたは 'getfeaturesの名前付きメソッドを提供するか、無名ブロックを提供したいかによって、上で与えたスタイルを使うか、または' initialize'を書いてブロックを受け入れることができるはずです'機能です。詳細が必要な場合は、私に知らせてください。 – mikej

3

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 
2

あなたは、Pythonから翻訳している場合は、する必要がありますPythonを学ぶのでではなく、「完全に無知」です。ショートカットはありません。

+1

はい、あなたは正しいです。私は学び始めます。 – zono

関連する問題