2016-10-14 1 views
-3

私は、Pythonでindex()を使用するためにインポートする必要はありますか?

import clr 
    import System 
    import ServiceDesk 
    import BaseModel 
    class Model(BaseModel.Model): 
     def ExecuteCustomAction(self,args,env): 
     resault = self.account.ExecuteService('service',args,env) 
     res = {} 
     if resault.Count>0: 
      for customaction in resault.Rows: 
       CustomActions = customaction['CustomActions'] 
       if CustomActions !="": 
        Lable = self.find_between(CustomActions, "Lable", "d") 
        CallBack = self.find_between(CustomActions, "CallBack", ";") 
        Action = self.find_between(CustomActions, "Action", "f") 
        res['Lable'] = Lable 
        res['CallBack'] = CallBack 
        res['Action'] = Action 
     return res 

    def find_between(text, first, last ,self): 
     try: 
      start = text.index(first) + len(first) 
      end = text.index(last, start) 
      return text[start:end] 

     except ValueError: 
      return "" 

を、以下の目的球を呼んでいるが、私はこれを実行すると、それは私がインポートする必要がありますかどう

オブジェクトが属性 'インデックス'

を持っていないと言いますか?

+2

は、どのように関数を呼び出していますか?そのコードも追加してください。 – JRodDynamite

+0

「テキスト」は何もありませんが、メソッド 'index'はありません。それはおそらくあなたが考えるものではありません。 – RemcoGerlich

+2

何もインポートする必要はありません。メソッド 'index'を持つオブジェクトを渡す必要があります。 – deceze

答えて

2

このエラーは、間違った値textを渡すと表示されます。 textは、インデックスメソッドが機能するための文字列でなければなりません。例:あなたが使用しているコードでは

>>> def find_between(text, first, last ,self): 
...  try: 
...   start = text.index(first) + len(first) 
...   end = text.index(last, start) 
...   return text[start:end] 
...  except ValueError: 
...   return "" 
... 
>>> find_between("some_string", "s", "t", None) 
'ome_s' 

>>> find_between(123, "s", "t", None) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 3, in find_between 
AttributeError: 'int' object has no attribute 'index' 

>>> find_between(None, "s", "t", None) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 3, in find_between 
AttributeError: 'NoneType' object has no attribute 'index' 

、おそらく、CustomActionsはオブジェクトではなく、文字列です。関数にオブジェクトを渡すと、文字列ではないためエラーが発生します。文字列でないことを確認するには、type(CustomActions)を使用してそのタイプを確認できます。また


、その自己に注意してください最初のパラメータである必要がありますので、あなたの署名は次のように見ている必要があります。

def find_between(self, text, first, last): 
関連する問題