2017-12-31 254 views
0

私はOOPを学んでいます(通常は関数型プログラミングに使用されています)。この小さなスクリプトはここで実行されますが、オブジェクトにデータ値を永久に保存する方法がわかりません(この場合、オブジェクトのインスタンスの名前はcountで、インスタンスにself.countを格納しようとしています)。オブジェクトのインスタンスに値を正しく格納する方法は?

#! /usr/bin/python3 

class WordCounter: 
    def __init__(self, count = 0): 
     self.__count = count 

    def set_count(self, path): 
     try: 
      nfile = open(path, "r") 
     except: 
      print("Could not open file") 
     fileList = [] 
     lowerCaseList = [] 
     line = nfile.read() 
     fileList.append(line.split()) 
     nfile.close 
     lowerCaseList = [word.lower() for word in fileList[0]] 
     print(lowerCaseList) 
     self.count = len(lowerCaseList) 

    def get_word_count(self): 
     return self.count 

    def __str__(self): 
     return "Total word count is: " + str(self.__count) 

if __name__ == "__main__": 
    count = WordCounter() 
    print(count) 
    count.set_count("/home/swim/Desktop/word_counter.txt") 
    print(count.get_word_count()) 
    print(count) 

そして、ここでは、出力されます。

総単語数は次のとおりです、「テキスト 'の' 0

[ 'ここ'、 'で'、 'A'、 '房'、 「うまくいけば」、「すべて」、「それ」、「これ」、「得られる」、「数えられる」、「正しく」、「ここに」、「それは」など)

合計単語数:0

getとsetのメソッドが正しく動作しているのが分かります。しかし、self.count変数をcountオブジェクトに格納するにはどうすればよいですか?

get(set)はget/setの前後で0と評価されます。

私はSTR方法は、ラインcount.set_count( "/パス/に/私/テキスト/ファイル")

後にも何かアドバイスを16を印刷し期待していましたか?再び

self.count = count

+2

をそれぞれの方法でself.__countまたはself.countを使うのか?あなたは 'self.count = len(lowerCaseList)'と 'self .__ count = count 'という名前でプロパティを2回定義しましたが、おそらくそれらは同じものであることを意図していました。また、 'nfile.close'はcloseメソッドを呼び出すためのカッコが必要なのでファイルを閉じません。 – roganjosh

+0

カウントを格納するのに2つの変数を使用するのはなぜですか? –

+0

ありがとうroganjosh。私はダミーhahahaのように感じる。それを指摘していただきありがとうございます。 __str__メソッドを使用して16を正しく印刷し、インスタンスに正しく保存しました。 –

答えて

0
#! /usr/bin/python3 

class WordCounter: 
    def __init__(self, count = 0): 
     self.__count = count 

    def set_count(self, path): 
     try: 
      nfile = open(path, "r") 
     except: 
      print("Could not open file") 
     fileList = [] 
     lowerCaseList = [] 
     line = nfile.read() 
     fileList.append(line.split()) 
     nfile.close() 
     lowerCaseList = [word.lower() for word in fileList[0]] 
     print(lowerCaseList) 
     self.__count = len(lowerCaseList) 

    def get_word_count(self): 
     return self.__count 

    def __str__(self): 
     return "Total word count is: " + str(self.__count) 

if __name__ == "__main__": 
    count = WordCounter() 
    print(count) 
    count.set_count("/home/swim/Desktop/word_counter.txt") 
    print(count.get_word_count()) 
    print(count) 

感謝のroganjoshをself.countself.__countが同じプロパティことになっているが、与えられたことを指摘するために:あなたがにあなたの__init__文で1行を変更する場合

0

ありがとうございました異なる名前。あなたのinit方法で

0

はあなたがself.__count異なるself.countを使用し、あなたのgetterメソッドとsetterメソッド内のに対してあなたが__countを設定self.__count = countを使用しました。そして、あなたの__str__メソッドでは、self.__count__init__に設定して0に設定し、ゲッターまたはセッターでself.__countの値を決して変更しないでください。

だから、どちらかなぜ `STR(自己.__数)`と `ないSTR(self.count)`持ってそれぞれの方法で

関連する問題