2012-11-07 41 views
3
class makeCode: 
    def __init__(self,code): 
      self.codeSegment = code.upper() 
      if checkSegment(self.codeSegment): 
        quit() 
      self.info=checkXNA(self.codeSegment) 
    def echo(self,start=0,stop=len(self.codeSegment),search=None): #--> self not defined 
      pass 

不工作...Python代碼,自定義不

  • 它說,當它實際上是可變沒有定義;
  • 函數checkSegment如果輸入不是由核苷酸字母組成的字符串,或者包含不能在一起的核苷酸,則返回1;
  • 如果發生這種情況,它會退出,沒關係,它可以很好地工作;
  • 然後它分配信息(如果它是RNA或DNA),檢查函數checkXNA,返回帶有信息「dnaSegment」或「rnaSegment」的字符串;完美的作品。

但是,功能echo將被設計用於打印更具體的信息告訴我,自我沒有定義,但爲什麼?

回答

5

self未在函數定義時定義,您不能使用它來創建默認參數。

函數定義中的表達式在函數創建時評估爲,而不是在調用時,請參閱"Least Astonishment" and the Mutable Default Argument

使用以下技術來代替:

def echo(self, start=0, stop=None, search=None): 
    if stop is None: 
     stop = len(self.codeSegment) 

如果您需要支持None作爲一個可能的值stop(例如,如果明確指定Nonestop有效值),你需要選擇一個不同的唯一前哨使用方法:當函數或方法的定義被評估

_sentinel = object() 

class makeCode: 
    def echo(self, start=0, stop=_sentinel, search=None): 
     if stop is _sentinel: 
      stop = len(self.codeSegment) 
5

默認參數值進行評價時,即,當類被解析。

寫依賴於對象狀態的默認參數值的方法是使用None列爲定點:

def echo(self,start=0,stop=None,search=None): 
    if stop is None: 
     stop = len(self.codeSegment) 
    pass